I am trying to implement a secure route based on the right of the user. A user who doesn't have a specific right can't access that route. That's why I am passing the Right Name in a route (lazy module routing). But, I found that it's a bit complicated to get lazy route data. I had to subscribe to router events. But, after subscribing I am not finding a way to return false or true to Canactivate.
Here is my canActivate code:
canActivate() {
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this.activatedRoute),
map((route) => {
while (route.firstChild) {
route = route.firstChild;
}
return route;
}),
mergeMap((route) => route.data))
.subscribe((event) => {
const right = event.right; // getting the right name from the route data.
const rights = this.localStorageService.getLocalStorageItem('rights');
if (right) {
if (rights.includes(right)) {
// I need to return true from here
} else {
// I need to return false from here
}
}
});
}
And, this is my route code:
const routes: Routes = [{ path: ':id', component: ProfileComponent,
data: { right: 'VIEW_PROFILE' }, canActivate: [RightRouteGuardService]}];