Miguel Moura
Miguel Moura

Reputation: 39364

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

Using Angular 10 I have the following method:

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

  }));

}

I am getting the error:

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

How to solve this?

Upvotes: 1

Views: 70

Answers (1)

Rafi Henig
Rafi Henig

Reputation: 6414

Creating an inner Observable requires flattening, which could be achieved using SwitchMap/MergeMap operator, as demonstrated below:

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

    }));

}

Here's a great article about Understanding RxJS map, mergeMap, switchMap and concatMap

Upvotes: 1

Related Questions