【问题标题】:Angular Observable wait till it is finishedAngular Observable 等到它完成
【发布时间】:2018-09-18 17:31:41
【问题描述】:

我编写了一个小型 Angular 应用程序,我在其中从一个 rest api 获取数据。为此,我使用了 observables。我现在的问题是,它们是异步的。

let tempArray: boolean[] = [];
for (let i = 0; i < 3; i++) {
    this._myservice.checkData(data[i]).subscribe(
        result => {
            tempArray.push(result);
            console.log('Before');
            console.log(tempArray);
        },
            error => console.log(error),
    );
}
console.log('After');
console.log(tempArray);

我现在的问题是,订阅后的结果数据不在指定数组中,如下图所示。在不将整个代码写入订阅的情况下,如何解决这个问题?

【问题讨论】:

  • 你为什么需要那个?这是处理订阅中与 Observable 生成的值相关的任何代码的最佳方法。

标签: angular rest typescript http observable


【解决方案1】:

唯一的方法是使用async/await,基本上,它确实将所有代码放入订阅中,只是它在后台执行:

let tempArray: boolean[] = [];
const promises = Promise<bool>[];
for (let i = 0; i < 3; i++) {
    promises.push(this._myservice.checkData(data[i]).toPromise());
}

// now, we create a promise that groups the previous ones, and await for it:

try {
    tempArray = await Promise.all(promises);
} catch (err) {
    console.log(err)
}

console.log('After');
console.log(tempArray);

如您所见,async/await 与 promises 一起工作,而不是 observables,但很容易将它们转换为其他对象 - 您只需要确保导入来自 RxJStoPromise

你可以在这里https://basarat.gitbooks.io/typescript/docs/async-await.html阅读更多关于async/await的信息

【讨论】:

    【解决方案2】:

    您可以使用forkJoin 运算符。类似于Promise.all,但用于可观察对象。

    import { forkJoin } from 'rxjs/observable/forkJoin';
    
    forkJoin(
      this._myservice.checkData(data[0]),
      this._myservice.checkData(data[1]),
      this._myservice.checkData(data[2])
    ).subscribe(result => {
      // result[0] is the first result
      // result[1] is the second result
      // result[2] is the third result
    });
    

    【讨论】:

      猜你喜欢
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-29
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 2021-06-20
      相关资源
      最近更新 更多