Alonso Contreras
Alonso Contreras

Reputation: 675

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?

Upvotes: 0

Views: 476

Answers (1)

Ajvar1
Ajvar1

Reputation: 147

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

Upvotes: 3

Related Questions