Reputation: 41
I want to get boolean for canActivate() method but nothing is working. My code is:
login() {
return this.http.get<any>('http://localhost/auth');
}
and I want to do somthing like this:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.authenticationService.login().subscribe(
() => true,
() => false
);
}
What is the correct way to do this?
Upvotes: 1
Views: 387
Reputation: 1740
You don't need to subscribe in a canActivate
method from a route Guard : In fact, Guard can return Observable and Angular will subscribe to it.
Just use rxjs map
operator, such as :
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.authenticationService.login().pipe(
map(response => /* do your stuff and return true to allow route access */)
catchError(error => of(false)) // Auth failed : return false to prevent route access
)
}
See more here
Upvotes: 1