Angular:如何更好地处理嵌套的API调用,特别是如果后者依赖于前者的结果

问题描述 投票:2回答:2

我处于这种情况,我以嵌套格式编写api调用。鉴于api调用后者的要求取决于前者的结果,是否有更好的方法来处理这个问题?我特别希望找到一个干净而优雅的解决方案,以便更好地组织呼叫,这样我就可以避免嵌套

更新:

这是代表我想要更好地处理的真实情况的代码:

api调用表示应用程序的动作/流程应该是的顺序。有没有更好的方法来处理嵌套调用?

  dummyMethod(){
    activeModal.result.then((modalResult)=>{
      var payload = {
        id:modalResult.id,
        value:modalResult.value,
      }

      this.dataService.updateRelationship(payload)
      .subscribe(response =>{
        if(response.success){
          var payload:{
            otherId: response.someId,
            otherValue:response.someValue
          }
          this.dataService.doCleanup(payload)
          .subscribe(otherResponse => {
            if(otherResponse.success){
              var anotherPayload:{
                someOtherId: otherResponse.otherId,
                someOtherValue: otherResponse.otherValue,
              }
              this.dataService.fetchResults(anotherPayload)
              .subscribe(results => {
                // do something with results
              }, error => {
                // log error
              });
          }}, otherError => {
            // log error
          });
        }
      }, error => {
        // log error
      });
    });
  }
angular observable angular-httpclient
2个回答
4
投票

您通常使用pipe和flatMap(或任何适合您用例的运算符):

this.http.get(url)
  .pipe(
    flatMap((data: any) => this.http.get(url + data.whatever)),
    flatMap((data: any) => /* ... */)
  )
  .subscribe((data: any) => {
    console.log(data);
  });

对于不相互依赖的请求,您可以使用zip

zip(this.http.get('foo'), this.http.get('bar'))
  .subscribe(([foo, bar]) => ...)

-1
投票

您可以尝试使用promiseasyncawait。我发现这篇文章描述了你要做的事情:https://medium.com/@balramchavan/using-async-await-feature-in-angular-587dd56fdc77

所以你试图通过嵌套来做这样的事情:

getConditionalDataUsingPromise() {
    this.httpClient.get<Employee>(this.url).toPromise().then(data => {
      console.log('First Promise resolved.')
      if (data.id > 5) {
        let anotherUrl = 'http://dummy.restapiexample.com/api/v1/employee/23';
        this.httpClient.get<Employee>(anotherUrl).toPromise().then(data => {
          this.conditionalPromiseResult = data;
          console.log('Second Promise resolved.')
        });
      }
    });
  }

你会想要像这样重写它:

async getConditionalDataUsingAsync() {
    let data = await this.httpClient.get<Employee>(this.url).toPromise();
    if (data.id > 5) {
      let anotherUrl = 'http://dummy.restapiexample.com/api/v1/employee/23';
      this.conditionalAsyncResult = await this.httpClient.get<Employee>(anotherUrl).toPromise();
    }
    console.log('No issues, I will wait until promise is resolved..');
  }
© www.soinside.com 2019 - 2024. All rights reserved.