RxJS beginner here. I am using Angular 6, and am trying to figure out how to get Observable<T>
from Observable<Observable<T>>
. I'm not sure if this is even valid and I'm struggling to understand it conceptually, however it seems like a simple problem.
I've looked into switchMap, flatMap, forJoin, however I don't think they fit my needs.
What I'm trying to do is an Angular route guard, which will prevent users from accessing a route unless they have the necessary permissions. 2 dependencies are a user profile to get their info from, which is then used to fetch their permissions. This mix is resulting in the Observable of Observable issue. Here's what I've got:
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;
}
));
}
}