【问题标题】:How to trigger an event only when response is recieved from multiple APIs? [duplicate]如何仅在收到来自多个 API 的响应时才触发事件? [复制]
【发布时间】:2023-04-10 00:21:01
【问题描述】:

我正在开发一个组件,我需要在其中并行调用两个 API。而且我只想在两个 API 调用都解决后才调用一个方法。

ngOnInit() {
    this.serviceOne.someApi().subscribe((res) => {
        this.response1 = res;  
    });
    this.serviceTwo.someApi().subscribe((res) => {
        this.response2 = res;  
    });
}

我只想在 this.response1this.response2 被填充时调用方法。

目前,我使用if statement 将逻辑封装在方法中。

someMethod() {
    if(this.response1 && this.response2) {
        //logic
    }
}

并将someMethod() 放入两个 api 调用的 subscribe() 中。

实现这一目标的最佳方法是什么?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    你可以使用forkJoin来实现。

    试试这样:

    Working Demo

      ngOnInit() {    
        const request1 = this.serviceOne.someApi();
        const request2 = tthis.serviceTwo.someApi();
    
        forkJoin([request1, request2]).subscribe(data => {
          this.response1 = data[0];
          this.response2 = data[1];
          this.someMethod();
        });
      }
    

    【讨论】:

    【解决方案2】:

    与数组解构相同的答案。

    forkJoin([
      this.serviceOne.someApi(),
      this.serviceTwo.someApi(),
    ]).subscribe(data => {
        let [serviceOneResponse, serviceTwoResponse] = data;
        // use responses.
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-27
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 2018-01-01
      • 1970-01-01
      相关资源
      最近更新 更多