首页 > 解决方案 > Angular - 将多个连续的 API 调用合并为一个结果

问题描述

我正在学习 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));
  }

标签: angularrxjs

解决方案


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

// 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 操作一起使用的灵感。


推荐阅读