[英]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.