简体   繁体   中英

Return condition always is false into subscribe Angular CanActivate Guard

I have this method inside a ward that captures the current path and compares it to the user's available paths.

But since the condition is inside the subscribe I have asynchrony problems since my Hasaccess variable always remains as false since the.subscribe is executed later when the function has already returned the value.

@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
    }
 }

How can I solve this? How can I make it return only within my.subscribe?

What you need is return the observable containing true/false.

canActivate(): Observable<boolean>...

and inside

return this.router.events.pipe(
    map((event: any) => {
        if (event instanceof NavigationEnd) {
            let matchRoutes = routesAllowed.filter(route => route === this.router.url)
            return (matchRoutes.length > 0)
        }
    })
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM