2016-06-29 62 views
5

我在AngularJS 2 RESTClient實現基類從API使用此方法調用數據:AngularJS 2 ZoneAwarePromise代替一個布爾值

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

其中InfoDataBoolean是具有兩個屬性的類:

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

我有另一個班,我叫我的服務方法。 這個調用在我想從InfoDataBoolean中返回數據的方法中,而不是像這樣的InfoDataBoolean類。

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; 
    }); 
} 

console.log(isLogged())輸出:

ZoneAwarePromise {__zone_symbol__state:空,__zone_symbol__value:數組[0]}

但我想從我的方法isLogged()返回truefalse

我該怎麼做?

回答

9

不要忘記你的isLogged方法是異步的並返回一個承諾。爲了得到結果,你需要在其上註冊一個回調與then方法:

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

在你的情況,你顯示的承諾,返回的結果時,它會得到解決...