I have created a Auth Manager in Angular2 to restrict Component access directly . I am still new to angular and learning the concepts.
I was able to restrict the user if the user name is not correct. But i am not able to use the value returned by the canActivate Method in my component to display a message in my front end.
My AuthManager class
import { Injectable } from '@angular/core';
import { CanActivate,Router,ActivatedRouteSnapshot,RouterStateSnapshot } from '@angular/router';
@Injectable()
export class AuthManager implements CanActivate{
user = "user";
constructor(private router:Router){
}
canActivate(route:ActivatedRouteSnapshot,state:RouterStateSnapshot){
console.log("Comes Here");
if(this.user == "user"){
return true;
}else{
console.log("YOur are not authorized");
this.router.navigate(['/persons']);
return false;
}
}
}
I am able to see YOur are not authorized in log but how to use the value in a component.
My app.router.ts
{
path: 'persons/:id',
component: PersonDetailComponent,
canActivate:[AuthManager]
}
What i understood by the Question is that you want to display Some kind of Error Message to the User if the Auth Fails. @PierreDuc is correct.But i have a different approach to this.
what you can do is create a service class
authenticate.service.ts
make use of this class in your component and AuthManager
and in the component check the same
Hope this is what you where looking at . it not exactly the answer of the question but a way to solve your problem.