遍历Observable值并订阅新的Observable

时间:2018-12-02 09:31:47

标签: angular rxjs observable

让我们说如果Array中有一个Observable,那么对于该数组的每个值,它都希望进行API调用(再次返回Observable)。我将其分解为一个简单的示例。因为我需要遍历前observables个值,所以如何确保data包含实际数据,而不包含另一个可观察的数据?

我尝试了switchMapmergeMap等。

const observables = Observable.of([{ id: 1 }, { id: 2 }]);
const data = Observable.of('data');

observables.pipe(

  // I tried a lot, something like this
  map(values => {
    if(Array.isArray(values)) {
      values.map(value => value.data = data); // data will be an Observable
    }
    return values;
  })

).subscribe(result => {
  console.log(result) // I want: [{ id: 1, data: 'data' }, { ... }]
});

1 个答案:

答案 0 :(得分:1)

根据您发送API请求的要求,您可以使用mergeMap,concatMap,forkJoin等中的任何一个。

我将使用forkJoinmergeMap

举例说明
const observableData: Observable<{id: number, data?: any}[]> = of([{ id: 11 }, { id: 12 }]);
return observableData.pipe(
  mergeMap(values => {
    // first map all the observales to make an array for API calls
    let apiArray = values.map((eachValue) => {
      return this.yourApiService.getData(eachValue.id)
    })
    // now you have to make API calls
    return forkJoin(...apiArray).pipe(
      map(apiData => {
        // now modify your result to contain the data from API
        // apiData will be an array conating results from API calls
        // **note:** forkJoin will return the data in the same sequence teh requests were sent so doing a `forEach` works here
        values.forEach((eachOriginalValue, index) => {
          eachOriginalValue.data = apiData[index].name  // use the key in which you get data from API
        });
        return values
      }),
      catchError((e) => {
          console.log("error", e);
          return of(e)
      })
    )

  })
);

在此处查看有效的示例:https://stackblitz.com/edit/forkjoinwithmergemap?file=src%2Fapp%2Fapp.component.ts