angularangular-routercanactivate

Angular Router route guard CanActivate always returns false


I have used CanActivate to protect a page but it always returning false because of that I can not access the protected router. I tried many ways, but was not successful to fix the issue. I am new to angular and I am stuck in validating the condition if (data.hasPermission == true).

Can any one please help me?

auth.service.ts

//Checking user access
getUserAccess(name: string): Observable<any> {
    return this.http.get(`api/${name}/useraccess`).pipe(
        map(
            (response: any) => {
                return response;
            },
        ),
    );
};


checkUserPermission() {
    this.getUserAccess(this.name).subscribe(data => {
        this.hasaccess = false;
        if (data.hasPermission == true) {
            this.hasaccess = true;
        } else {
             this.hasaccess = false;
        }
    });

    return this.hasaccess
}


isUserHasAccess(): boolean {
    return this.hasaccess
}

auth.guard.ts

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (this.authService.isUserHasAccess()) {
        return true;
    } else {
        return false;
    }
}
json data from API

{"hasPermission":true}


Solution

  • You're returning a static value, you're not waiting for the async task to complete.

    Look closely at the docs, canActivate can also return an Observable that resolves to true or false, this allows you to do async checks.

    Try this instead:

    checkUserPermission() {
        return this.getUserAccess(this.name).pipe(map(data => data.hasPermission === true))
    }
    
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        return this.authService.checkUserPermission();
    }
    

    The Angular Router will subscribe to that Observable, you don't have to. All you have to do is map it to a function that returns a boolean.