【问题标题】:Rxjs Convert Observable<any>[] to Observable<any[]>Rxjs 将 Observable<any>[] 转换为 Observable<any[]>
【发布时间】:2018-08-23 08:10:47
【问题描述】:

假设我们有两个接口:

export interface IA{
   something: string;
   myprop: number;
}

export interface IB{
   myprop: number;
}

我有一个方法应该调用从后端返回 IA 对象的端点,然后它应该调用另一个端点,然后将两个结果合并到 IA 对象中。以前我在做这样的事情:

GetA():Observable<IA>{
    return this.httpClient
        .get<IA>('somewhere')
        .concatMap(a=>Observable.combineLatest(
           Observable.of(a), 
           GetB(a)
        ))
        .map([a,b]=>combineSomehowAandB(a,b))
}

但是现在,有了新版本的rxjs,我不得不改用 .pipe(operators[]) 。如何用 pipe() 实现相同的功能?我试过这样,但它不起作用:

GetA():Observable<IA>{
    return this.httpClient
        .get<IA>('somewhere')
        .pipe(
           concatMap(a=>[Observable.of(a), GetB(a)]),
           combineLatest(),
           map([a,b]=>combineSomehowAandB(a,b))
         );
}

提前致谢。

【问题讨论】:

    标签: angular typescript rxjs pipe combinelatest


    【解决方案1】:

    看起来您只是没有将原始链正确地重写为 RxJS 6:

    return this.httpClient.get<IA>('somewhere')
      .pipe(
        concatMap(a => combineLatest(of(a), GetB())),
        map(([a,b]) => combineSomehowAandB(a,b)),
      );
    

    单独使用combineLatest()没有任何参数是没有用的。

    【讨论】:

      【解决方案2】:

      使用of 代替observable.of

      GetA():Observable<IA>{
          return this.httpClient
              .get<IA>('somewhere')
              .pipe(
                 concatMap(a=> combineLatest(
                    of(a), 
                    GetB()
                 )),
                 map([a,b]=>combineSomehowAandB(a,b))
               );
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-10
        • 2018-07-16
        • 2021-05-24
        • 2018-08-14
        相关资源
        最近更新 更多