RxJS 新手在这里。使用 Angular 6。试图弄清楚如何Observable<T>
从Observable<Observable<T>>
. 不确定这是否有效并且难以从概念上理解它,但这似乎是一个简单的问题。
我研究了 switchMap、flatMap、forJoin,但我认为它们不符合我的需求。
我正在尝试做的是一个 Angular 路由保护,它将阻止用户访问路由,除非他们拥有必要的权限。2个依赖项是一个用户配置文件,用于获取他们的信息,然后用于获取他们的权限。这种混合导致了 Observable 的 Observable 问题。这是我所拥有的:
export class AuthPermissionsRouteGuard implements CanActivate {
constructor(
private router: Router,
private authService: AuthPermissionsService,
private openIdService: AuthOpenIdService) {}
/**Navigates to route if user has necessary permission, navigates to '/forbidden' otherwise */
canActivate(routeSnapshot: ActivatedRouteSnapshot): Observable<boolean> {
return this.canNavigateToRoute(routeSnapshot.data['permissionId'] as number);
}
/**Waits on a valid user profile, once we get one - checks permissions */
private canNavigateToRoute(permissionId: number): Observable<boolean> {
const observableOfObservable = this.openIdService.$userProfile
.pipe(
filter(userProfile => userProfile ? true : false),
map(_ => this.hasPermissionObservable(permissionId)));
// Type Observable<Observable<T>> is not assignable to Observable<T> :(
return observableOfObservable;
}
/**Checks if user has permission to access desired route and returns the result. Navigates to '/forbidden' if no permissions */
private hasPermissionObservable(permissionId: number): Observable<boolean> {
return this.permissionsService.hasPermission(permissionId).pipe(
map(hasPermission => {
if (!hasPermission) {
this.router.navigate(['/forbidden']);
}
return hasPermission;
}
));
}
}
非常感谢!!