【问题标题】:Angular - merge multiple consecutive API calls into one resultAngular - 将多个连续的 API 调用合并为一个结果
【发布时间】:2020-12-28 18:24:02
【问题描述】:

我正在学习 rxjs,目前面临一些我不太确定如何解决的问题。我需要调用多个 API 请求,但问题是首先我需要获取名称列表,然后为每个名称获取其余数据。到目前为止,我已经提出了两个map 函数,第一个调用将获取名称列表,第二个map 将遍历列表并调用另一个请求以获取其余数据。我认为这是不好的做法,但我不明白如何使用 mergeMapforkjoin 来实现更好的功能代码。

  public getNames(): Observable<any> {
    return this.httpClient.get<response>(someUrl)
                          .pipe(map(res => res.results), map((data)=>{
                              data.forEach(dat => {
                               this.getDataByName(dat.name).subscribe(res => {
                                  dat.image = res.image;
                               });
                              });
                              return data;
                            }));
  }
  
  public getDataByName(name): Observable<any> {
    return this.httpClient.get<any>(urlToGetMoreDataByName)
                          .pipe(map(res => res.results));
  }

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    如果我理解你的问题,我会尝试这些方面的东西

    // remove the specification of the return type (: Observable<any>) since you
    // should be able to achieve a more precise result using Typescript 
    // type inference
        
    public getNames() {
      return this.httpClient.get<response>(someUrl).pipe(
            map(res => res.results),
            // transform "data", which is an array of names in an array of Observables
            // this first map is the rxjs map operator
            map((data)=> {
               // this inner map is the javascript method of the array
               // for each dat it returns an Observable which emits when getDataByNme returns
               return data.map(dat => this.getDataByName(dat.name).pipe(
                                        // this is an rxjs map operator which retuns a
                                        // dat object with the image property set
                                         map(res => {
                                           dat.image = res.image;
                                           return dat
                                         })
                                      )
               )
           }),
           // concatMap is used here to make sure that we fire the execution of the 
           // Observable created by forkJoin after the first get operation has returned
           concatMap(arrayOfObservables => forkJoin(arrayOfObservables))
         );
    }
    

    现在getNames 返回一个 Observable,一旦所有获取图像的调用都已执行,它就会发出。使用forkJoin,我们确保我们并行启动所有http get 操作。我们可以使用其他运算符,例如`mergeMap,如果我们想控制并发级别。

    您可能会发现一些关于哪些运算符可以与http操作in this article一起使用的灵感。

    【讨论】:

      【解决方案2】:
       this.campaignService.getCampaignDetailById(this.data.campaignId).subscribe((response: any) => {
            if (response && response.data && response.data.length > 0) {
              this.campaignService.getCampaignSessionDetailById(response.data[0].session_id).subscribe((response: any) => {
                if (response && response.data && response.data.length > 0) {
                  // second param
                  this.campaignMockupCatalog = response.data[0]['shrt-campaign-mockup-catalogs'];
      
                  let designMockupTypeId = response.data[0]['shrt-campaign-mockup-catalogs'].map((data) => data.design_mockup_type_id);
                  this.campaignService.getMockupTypes().subscribe((response: any) => {
                    if (response && response.data && response.data.length > 0) {
                      let shrtCampMockupType = response.data.find((data) => data.id == designMockupTypeId);
                      // first param
                      this.campaignMockupTypes = shrtCampMockupType['shrt-campaign-mockup-type'].map((data) => data);
                    }
                  });
                }
              })
            }
          })
      
      

      【讨论】:

        猜你喜欢
        • 2019-05-09
        • 2017-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多