【问题标题】:Trying to understand the Promise in angular 2试图理解 Angular 2 中的 Promise
【发布时间】:2016-08-29 21:46:50
【问题描述】:

我为 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 中添加seTimeout 时,我可以在视图中获得我想要的数据。有人可以帮助我处理这段代码,或者建议我使用 Observables 的更好方法。先感谢您。

【问题讨论】:

  • this._checkAuthApiService.loadSheetsApi 是做什么的?
  • 你使用了一些 promise polyfill 吗?
  • this._checkAuthApiService.loadSheetsApi 正在从 google api 返回工作表数据。最后 res.result.values 包含我需要的数据,但是由于是异步调用,因此数据稍后可用,我正在使用上面的 setTimeout 对其进行测试,它可以工作,我得到了我需要的东西。问题仍然存在于未正确触发或我遗漏了某些内容的 promise 调用上。
  • 你为什么在loadSheetsFunc()中使用new Promise()

标签: javascript angular typescript angular-promise observable


【解决方案1】:

setTimeout() 导致一个完整的 Angular2 更改检测周期,这就是为什么这会使 Angular2 识别更新的属性。

如果没有setTimeout(),Angular2 无法识别更新,这表明 polyfill 存在问题(可能是加载顺序)。

我会对您的代码进行一些更改

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)。

【讨论】:

    猜你喜欢
    • 2017-11-16
    • 1970-01-01
    • 2018-04-11
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 2016-11-10
    相关资源
    最近更新 更多