角:从forkJoin返回的值在其他可观察到的管道内

问题描述

这是我需要实现的方案:

  1. 调用一个API,该API返回带有对象数组的响应
  2. 我将这些对象映射到另一个对象数组
  3. 对于此新对象数组的每一项,我需要调用一个API调用
  4. 第二个调用的响应必须在2中创建的数组的每个对象中设置一个值。
  5. 我想从4返回一个可观察对象数组。

到目前为止,我已经能够创建以下内容

public getWishlist ( receiver : Person) : Observable<Wish[]>{
    return this.http$.get<IWishlistResponse[]>(environment.apiUrl + 'wishlist/' + receiver.id).pipe(
      map( (response) => {
        let wishes: Wish[] = [];
        response[0].wishes.forEach((wish) => {
          wishes.push(new Wish(
            wish._id,wish.title,wish.price,null,wish.url
          ));
        });
        return wishes;
      }),tap( (wishes) => {
        let wishStateObservables = wishes.map(wish => this.http$.get<wishStatus>(environment.apiUrl + 'wish/' + wish.id + '/state').pipe(catchError(() => of(null))));
        forkJoin(wishStateObservables)
          .pipe(
            map(states => {
              states.forEach((state,index) => {
                wishes[index].status = state;
              });
              return wishes;
            })
          ).subscribe((wishes => { console.log(wishes) }));
      })
    );

console.log中的forks订阅中的“愿望”是我想在可观察对象中返回的值,但是我无法在此可观察对象中获取它们。 所以我应该使用什么代替“ tap”运算符。能够将forkJoin管道的结果放入可观察到的返回值中?

解决方法

尝试将tap切换为switchMap,后者会切换到新的可观察对象。

import { switchMap } from 'rxjs/operators';
...
public getWishlist ( receiver : Person) : Observable<Wish[]>{
    return this.http$.get<IWishlistResponse[]>(environment.apiUrl + 'wishlist/' + receiver.id).pipe(
      map( (response) => {
        let wishes: Wish[] = [];
        response[0].wishes.forEach((wish) => {
          wishes.push(new Wish(
            wish._id,wish.title,wish.price,null,wish.url
          ));
        });
        return wishes;
      }),switchMap( (wishes) => { // change to switchMap to switch to new observable
        let wishStateObservables = wishes.map(wish => this.http$.get<wishStatus>(environment.apiUrl + 'wish/' + wish.id + '/state').pipe(catchError(() => of(null))));
        return forkJoin(wishStateObservables); // add return here to return for the switchMap
      }),map(states => { // remove the inner pipe from the forkJoin and put the pipe in outer pipe
              states.forEach((state,index) => {
                wishes[index].status = state;
              });
              return wishes;
      }),);