代码之家  ›  专栏  ›  技术社区  ›  Maris

Rxjs将可观测的<any>[]转换为可观测的<any[]>

  •  1
  • Maris  · 技术社区  · 6 年前

    假设我们有两个接口:

    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))
             );
    }
    

    2 回复  |  直到 6 年前
        1
  •  1
  •   martin    6 年前

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

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

    使用 combineLatest() 没有任何参数本身是无用的。

        2
  •  0
  •   Sachila Ranawaka    6 年前

    使用 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))
             );
    }