[英]Trying to understand the Promise in angular 2
I have created a service for google API and stacked at the promise response. 我已经为Google API创建了一个服务,并堆积在promise响应中。 Let me show you my code: 让我向您展示我的代码:
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;
not sure what i am missing but when i add seTimeout
within ngOnInit
ti works i get the data i want on the view. 不知道我缺少什么,但是当我在ngOnInit
ti中添加seTimeout
,我得到了我想要的数据。 Can someone help me with this code or perhaps suggest me a better way using Observables. 有人可以通过这段代码为我提供帮助,还是可以建议我使用Observables的更好方法。 Thank you in advance. 先感谢您。
The setTimeout()
causes a full Angular2 change detection cycle, which is why this makes Angular2 recognize the updated property. setTimeout()
会导致整个Angular2更改检测周期,这就是为什么这会使Angular2识别更新的属性。
That Angular2 doesn't recognize the update without setTimeout()
indicates an issue with polyfills (perhaps loading order). 如果没有setTimeout()
Angular2将无法识别更新,这表明polyfills存在问题(可能是加载顺序)。
I would make a few changes to your code 我会对您的代码进行一些更改
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;
}
I don't know though what loadSheetsApi()
returns (assuming Observable
). 我不知道loadSheetsApi()
返回什么(假设Observable
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.