类型'Observable <Observable <Response >>'不可分配给类型'Observable <Response>'

问题描述

使用Angular 10,我有以下方法

private getUser() : Observable<Response> {

  return this.authenticationService.getClaims('sub').pipe(map((claims: Claim[]) => {

    let request: Request = { userId: 1 };

    return this.userService.getByUserId(request).pipe(
      map((payload: Payload<Response[]>) => payload.result[0])
    );

  }));

}

我遇到了错误

Type 'Observable<Observable<Response>>' is not assignable to type 'Observable<Response>'.

如何解决这个问题?

解决方法

创建内部Observable需要展平,这可以使用SwitchMap / MergeMap运算符来实现,如下所示:

private getUser() : Observable < Response > {

  return this.authenticationService.getClaims('sub').pipe(
    switchMap((claims: Claim[]) => {

      let request: Request = { userId: 1 };

      return this.userService.getByUserId(request).pipe(
        map((payload: Payload<Response[]>) => payload.result[0])
      );

    }));

}

关于Understanding RxJS map,mergeMap,switchMap and concatMap

的精彩文章