Troubleshooting Clarifai object error while invoking "model.predict" within Angular Framework

I've been attempting to utilize Clarifai's color API to extract the different colors present in an image. Unfortunately, I am encountering challenges when trying to call the API, as it consistently returns empty objects.

Below is the snippet of code that I've been using to make the API call:

private app;

obj: RootObject;

constructor(private _http: HttpClient) {
    this.app = new Clarifai.App({
        ApiKey: "CENSOR BAR"
    });
};

public getColorValues(imageUrl: string): RootObject {
    this.app.models.predict('eeed0b6733a644cea07cf4c60f87ebb7', imageUrl).then(
        function (response) {
            this.obj = response;
        },
        function (error) {
            this.obj = "There was an error";
        }
    );
    let i: number;
    while (this.obj == null) {
        i += 1;
    }
    console.log("Waited " + i + " cycles for response.")
    console.log("Object: " + this.obj);
    return this.obj;
}

Answer №1

It appears that the call is designed to be asynchronous, however, you are treating it as a synchronous call. As a result, the returned this.obj may not be properly set when you return it.

Furthermore, the this.obj may never get set at all, due to your use of the function keyword which alters the reference of this to the local function.

The getColorValues function should only return a Promise<RootObject>:

getColorValues(imageUrl: string): Promise<RootObject> {
  return this.app.models.predict('eeed0b6733a644cea07cf4c60f87ebb7', imageUrl);
}

Simply follow these steps and you should be good to go. When calling the getColorValues function, ensure you do so like this:

getColorValues(imageUrl).then((resp) => {
  this.obj = resp;
  // this.obj now holds the desired value
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is Angular 4 failing to set headers properly or is Express.js searching in the wrong place?

When interacting with an Express.js API, I encountered a issue regarding the handling of auth tokens. The problem arose when sending the token in the request headers using Angular 4 compared to Postman. In Postman, setting the header named 'Authorizat ...

Combine two closely related functions into a single function

I'm dealing with two very similar functions: setEndTimesAndStartTimes(pricerules: PriceRule[], type: string) { this.endTimes = []; this.startTimes = []; pricerules.forEach(pricerule => { if (type === 'end') { ...

Assign a specific HTML class to serve as the container within an Angular directive

Is there a way to dynamically add and set an HTML class using an Angular directive with a parameter? Let's consider a scenario where we have a div with an existing class but no directive: <div class="myClass"></div> Now, if we w ...

Tips for enabling custom object properties in Chrome DevTools

In my typescript class, I am utilizing a Proxy to intercept and dispatch on get and set operations. The functionality is working smoothly and I have successfully enabled auto-completion in vscode for these properties. However, when I switch to the chrome d ...

Tips for getting Angular's HttpClient to return an object rather than a string?

How can I make HttpClient return the data in JSON Object format? The Angular documentation states that HttpClient should automatically parse returned JSON data as an object. However, in my project, it only returns the data as a string. Although using JSO ...

I need help figuring out how to incorporate dynamic checkboxes in Angular

Currently, I am working on integrating dynamic forms into my Angular application and I am referring to the https://angular.io/guide/dynamic-form guide for guidance. Specifically, I have a checkbox question that consists of more than four options to choose ...

Tips for transferring state information from a client to a server component within Nextjs?

Currently, I am working on a project where I need to read and write data from a locally stored .xml file that contains multiple <user> tags. The technology stack includes TypeScript and NextJS. The project is divided into three main components sprea ...

Enhancing React with TypeScript: Best Practices for Handling Context Default Values

As I dive into learning React, TypeScript, and Context / Hooks, I have decided to create a simple Todo app to practice. However, I'm finding the process of setting up the context to be quite tedious. For instance, every time I need to make a change t ...

The file could not be located on the server during the project build and upload process

Presently, I'm engrossed in a project involving Angular 9 and ASP Core 3. You can find the website at: Nevertheless, encountering an error when trying to access this URL: http://mag-testcpl.astromap.ir/assets/vendors/global/toastr.css The culprit ...

Angular2 combined with redux fails to produce any outcomes

Currently, I am implementing redux in conjunction with angular2 and attempting to make a call to Windows Azure Search. Below is the snippet of code that I have written: types.ts export interface IAppState { languageState?: LanguageState; searchState? ...

Working with varying amounts of JSON data in REST services

I need to consume a REST web service with JSON type where the input JSON has a different number of values each time. For example: {"name":"x","age":23,"language":"java"} or {"name":"c","age":"34","language":"c++","db":"oracle"} The input JSON may vary ...

I encountered an issue while making customizations to my default next.config.js file. Despite attempting various solutions, I consistently encountered an error regarding the invalid src property

I'm currently trying to introduce some custom configurations into the next.config.js file. However, I keep encountering an error regarding an invalid src prop. Despite my attempts to troubleshoot in various ways, the error persists. // ...

What is the best way to showcase a standalone JSON object within the template?

I have a detailed component that is designed to show the 5-day forecast for a specific city. I have successfully retrieved the data using the http.get(Url) method. However, I am unsure of how to bind this JSON data to my view. I am familiar with displayi ...

What are the steps to expand the express object with TypeScript?

I am facing an issue where, after compiling a typescript project, the express import import {Request, Response} is not showing up. I am now attempting to use require, but I am unsure of how to extend the express object and utilize req and res. Any assistan ...

utilizing $inject method along with supplementary constructor parameters

After referencing the answer found here: Upon implementing the $inject syntax, my controller code appears as follows: class MyCtrl { public static $inject: string[] = ['$scope']; constructor($scope){ // implementation } } // register ...

The resend email feature isn't functioning properly on the production environment with next js, however, it works seamlessly in the development environment

import { EmailTemplate } from "@/components/email-template"; import { Resend } from "resend"; const resend = new Resend("myApiKey"); // this works only in dev // const resend = new Resend(process.env.NEXT_PUBLIC_RESEND_API_KE ...

Nuxt3 - TS2339: The 'replaceAll' property is not found on the 'string | string[]' type in Nuxt3

Hey there! I've been experimenting with the replaceAll() method within my Nuxt3 project and encountered a strange error. Folder Structure ───pages │ └───Work │ │ index.vue │ │ [Work].vue Template <templat ...

Unable to globally install @angular/cli using Node.js on Red Hat software collection

After installing node.js 8 from Red Hat Software Collection (rh-nodejs8), I encountered an issue where I couldn't globally install TypeScript or @Angular/CLI because my bash session was restricted by scl-utils, requiring admin rights for global instal ...

Error 404: The Magento REST API sample code is not available

As I was following the guidelines provided at , I encountered an issue with the sample code below. It returns a 404 error when attempting to call the URLs /oauth/initiate and /admin/oauth_authorize. Although /api/rest functions correctly, thanks to the cu ...

Obtaining the response header in Angular 7 using flatMap

I am attempting to access the response header inside flatMap this.http.post<HttpResponse<any>>(`${environment.URL_API}/patients/v1/`, patient, {observe: 'response'}).pipe( flatMap((res: any) => { console.log(res) var loca ...