Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS 2 ZoneAwarePromise instead a boolean value

Tags:

angular

I have a base class in AngularJS 2 for restClient to call data from API with this method:

public getInfoDataBooleanRequest(url: string): InfoDataBoolean {
  return this.http.get(this.urlApiPrefix + url, this.createRequestOptions())
      .toPromise()
      .then(response => <InfoDataBoolean>response.json())
      .catch(this.handleError);
}

where InfoDataBoolean is a class with two properties:

export class InfoDataBoolean {
    public data: boolean;
    public error: string;
}

I have another class where I called my service method. This call is inside a method where I want to return the data from InfoDataBoolean, not the class InfoDataBoolean like this.

public isLogged(): boolean {
   return this.getInfoDataBooleanRequest('islogged').then(x => {
      let result: InfoDataBoolean = x;

      if(result.error !== "1") {
        console.log('Success is failed');
        return false;
      }

      return result.data;
   });
}

The output of console.log(isLogged()):

ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array[0]}

But I want to return true or false from my method isLogged().

How can I do this?

like image 738
Sébastien Avatar asked Jun 29 '16 13:06

Sébastien


1 Answers

Don't forget that your isLogged method is asynchronous and return a promise. To get the result you need to register a callback on it with the then method:

console.log(isLogged());
isLogged().then(data => {
  console.log(data);
});

In your case, you display the promise and the returned result when it will be resolved...

like image 133
Thierry Templier Avatar answered Oct 23 '22 06:10

Thierry Templier