类型 'Observable<Observable<Response>>' 不可分配给类型 'Observable<Response>'
Type 'Observable<Observable<Response>>' is not assignable to type '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
的精彩文章
使用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
的精彩文章