【问题标题】:RxJS - Conditional Concat and merge objects from responseRxJS - 条件 Concat 并合并响应中的对象
【发布时间】:2021-04-21 23:32:15
【问题描述】:

我目前正在开发一个 ionic 5 应用程序,我有 2 个可观察对象,它们返回 2 个不同对象类型的数组。 我想将对象的一些属性混合在一个新类型的对象中,但我只想在第一个返回值时对服务器进行第二次调用。

例子:

obs1$: Observable<{id: string, name: string, active: boolean}[]>;
obs2$: Observable<{id: string, location: Location, year: date}[]>;

newObs$: Observable<{id: string, name: string, year: date}[]>;

我想要:

  1. 致电obs1$
  2. 如果obs1$返回值则调用obs2$,否则返回[]
  3. obs2$返回值时,返回两个observable的对象映射结果数组

【问题讨论】:

    标签: angular typescript ionic-framework rxjs observable


    【解决方案1】:

    我添加了一些接口以使代码更易于阅读。我在这里假设您的第一个 observable 在没有值时返回一个空数组。如果它返回 null,您可能需要删除 switchMap 中的 .length

    以下代码可以正常工作。

    interface First {
      id: string;
      name: string;
      active: boolean;
    }
    interface Second {
      id: string;
      location: Location;
      year: Date;
    }
    interface Result {
      id: string;
      name: string;
      year: Date;
    }
    
    ...
    const first$: Observable<First[]>;    // Make sure it's initialized
    const second$: Observable<Second[]>;  // Make sure it's initialized
    ...
    
    const result$: Observable<Result[]> = first$.pipe(
      switchMap(firstArray => !firstArray.length
        ? of([])
        : second$.pipe(
            map(secondArray => firstArray
              .filter(a => secondArray.some(b => a.id === b.id))
              .map(a => ({ first: a, second: secondArray.find(b => a.id === b.id) }))
              .map(values => ({...values.first, year: values.second.year }))
            )
        )
      )
    );
    

    【讨论】:

      【解决方案2】:

      我猜你在上课。你可以做这样的事情。但请确保在映射之前初始化您的 observables。

        obs1$: Observable<{ id: string; name: string; active: boolean }[]>; 
        obs2$: Observable<{ id: string; location: Location; year: Date }[]>;
      
        newObs$ = this.obs1$.pipe(
          switchMap((item) => {
            const emptyArray: { id: string; name: string; year: Date }[] = [];
            return item? this.obs2$.pipe(
                  map((item2) => {
                    const others = item2.map((ent2) => {
                      const index = item.findIndex(ent1 => ent1.id === ent2.id)
                      let name = ''
      
                      if(index !== -1){
                        name = item[index].name
                      }
                      const id = ent2.id;
                      const year = ent2.year;
                      return {name, id, year}
                    });
      
                    return others
                  }),
                )
              : of(emptyArray);
          }),
        );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-29
        • 2017-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-21
        • 1970-01-01
        • 2021-06-25
        相关资源
        最近更新 更多