【问题标题】:How to use Async in Angular如何在 Angular 中使用异步
【发布时间】:2021-08-27 14:02:04
【问题描述】:

假设我想进行 2 个返回数据的 http 调用,并且我只想在两个 http 调用都返回数据后调用一个函数,以便我可以合并两个数据。

 ngOnInit(): void {
    this.getData();
  }



getData() {

this.func1();
this.func2();
this.func3();

}

async func1() {
 this.service.call1().subscribe((data) => {
    this.data1 = data;
  });

}

async func2() {
  this.service.call2().subscribe((data) => {
    this.data2 = data;
  });
}

func3() {
//this should only get called when func1 and func2 have finished their http calls.
}

【问题讨论】:

  • edit您的问题标题不仅仅是重复标签中可用的信息。您的标题应该描述您遇到的问题或您提出的问题,这种方式对正在扫描搜索结果列表以试图找到解决问题的本网站的未来用户有意义。您当前的标题在这方面没有任何作用 - 它只是标签的反刍。
  • @Jay 不知道为什么你改变了接受的答案。我的回答有什么遗漏吗?

标签: angular asynchronous async-await


【解决方案1】:

你应该使用 RxJS forkJoin 来实现你想要做的事情。

forkJoin 将等待所有通过的 observables 发出并完成 然后它会发出一个数组或一个对象,最后一个值来自 对应的 observables。

在角度你subscribe(等待)到一个可观察的值来接收数据。在您的示例中,一旦从服务器收到响应,就会执行 subscribe 中的任何内容。


如果 `func3` 不是 Observable

forkJoin([this.func1(),this.func2()]).subscribe(results => {
    let data1 = results[0];
    let data 2 = results[1];
    this.func3();
});

如果 `func3` 是一个 Observable,你必须通过管道传递你的调用

this.subscription.add(
        forkJoin([this.func1(),this.func2()])
            .pipe(
                switchMap(results => {
                    let data1 = results[0];
                    let data2 = results[1];
                    return func3();  
                 }
            ))
            .subscribe((value3) => {
                // value returned from the func3() observable
            })
    );

注意:不要忘记取消订阅您的所有订阅onDestroy

【讨论】:

  • 我在 Angular TypeScript 中一直使用 try catchasync await。订阅会在彼此之间创建回调链。
  • @xinthose 编辑了异步等待评论。我使用 RxJS 管理订阅链。
【解决方案2】:

这是最新的 angular 语法

    forkJoin([httpcall1,httpcall2... httpcalln])
          .subscribe((resultArray) => {

            //once the data are recived they will be in the result array in order of the call
            console.log(resultArray[0]);
            console.log(resultArray[1]);
            
});

【讨论】:

    【解决方案3】:

    获取数据后可以在func1里面调用func2,在func2里面调用func3,这样就可以一个一个的工作了

    getData() {
    this.func1();
    }
    
    func1() {
    this.service.call1().subscribe((data) => {
       this.data1 = data;
    this.func2();
    });
    
    func2() {
    this.service.call2().subscribe((data) => {
       this.data2 = data;
    this.func3();
    });
    
    func3() {
    // Your code here
    }
    

    【讨论】:

    • 我正在尝试了解如何在这种情况下使用 async/await
    • 我找到了这个答案stackoverflow.com/a/35612484/7137373
    • 永远不要在订阅中订阅 observable!您将遇到随机失败的竞争条件。
    猜你喜欢
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 2019-01-21
    相关资源
    最近更新 更多