[英]Trying to understand the Promise in angular 2
我已經為Google API創建了一個服務,並堆積在promise響應中。 讓我向您展示我的代碼:
getPromise: Promise<any>;
loadSheets: Array<any>;
constructor(public _checkAuthApiService: CheckAuthApiService) { }
ngOnInit() {
if (this._checkAuthApiService) {
this._checkAuthApiService.checkAuth().then(res => {
if (res && !res.error) {
this.loadSheetsFunc();
}
});
}
//setTimeout(function(){},1000); //When i add this it works :(
}
loadSheetsFunc = () => {
this.getPromise = new Promise((resolve: any, reject: any) => {
resolve(this._checkAuthApiService.loadSheetsApi())
});
this.getPromise.then((res: any) => this.sheetsResults(res));
};
sheetsResults = (res: any) => this.loadSheets = res.result.values;
不知道我缺少什么,但是當我在ngOnInit
ti中添加seTimeout
,我得到了我想要的數據。 有人可以通過這段代碼為我提供幫助,還是可以建議我使用Observables的更好方法。 先感謝您。
setTimeout()
會導致整個Angular2更改檢測周期,這就是為什么這會使Angular2識別更新的屬性。
如果沒有setTimeout()
Angular2將無法識別更新,這表明polyfills存在問題(可能是加載順序)。
我會對您的代碼進行一些更改
loadSheets: Array<any>;
constructor(public _checkAuthApiService: CheckAuthApiService) { }
ngOnInit() {
if (this._checkAuthApiService) {
this._checkAuthApiService.checkAuth().then(res => {
if (res && !res.error) {
this.loadSheetsFunc();
}
});
}
}
loadSheetsFunc() {
this._checkAuthApiService.loadSheetsApi()
subscribe(val => this.sheetsResults(res));
}
sheetsResults(res: any) {
this.loadSheets = res.result.values;
}
我不知道loadSheetsApi()
返回什么(假設Observable
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.