0

I'm trying to call Clarifai's color API to receive the different colors in an image. However, I'm having some difficulty calling the API, as I'm always getting empty objects back.

This is the code used to call the API:

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;
}
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
MyNameIsGuzse
  • 273
  • 1
  • 5
  • 23

1 Answers1

1

The call is async, but you are handling it as a sync call. The returned this.obj has not been set when you return it.

Besides that, it won't be set at all, because you are using the function keyword which changes the this reference to the local function

Your getColorValues can only return a Promise<RootObject>:

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

And that's it, that's all you should need. When you call the getColorValues make sure to call it like this:

getColorValues(imageUrl).then((resp) => {
  this.obj = resp;
  // this.obj contains what you want
});
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • But now `getColorValues` doesn't return a value, and i get another error. – MyNameIsGuzse Nov 05 '18 at 09:23
  • getColorValues returns a Promise now, and yes, the promise itself resolves nothing, because you already stored it in the `this.obj`. Returning it from the promise doesn't add much. I'll update my answer to have it more to your liking perhaps – Poul Kruijt Nov 05 '18 at 11:09