In my UserAccessGuard class, I have a method that captures the current path and compares it to the user's available paths. However, I am facing asynchronous problems because the condition inside the subscribe block causes my Hasaccess variable to remain false since .subscribe is executed after the function has already returned the value.
How can I resolve this issue? Is there a way for the method to return only within the .subscribe block?
@Injectable() export class UserAccessGuard implements CanActivate {
constructor(private router : Router,
private commonSv : CommonSv) {}
canActivate() : boolean {
const routesAllowed = this.commonSv.getRoutesAllowed(); //list of strings
let hasAccess: boolean = false;
this.router.events.subscribe(
(event: any) => {
if (event instanceof NavigationEnd) {
let matchRoutes = routesAllowed.filter(route => route === this.router.url)
hasAccess = (matchRoutes.length > 0)
}
});
return hasAccess; //always false because subscribe is executed more last
}
}