As far as I understand it the CanActivate interface in Angular2 is only effective on route changes. So if I have a page p that requires the user to be logged in I can create a guard that implements the CanActivate interface which will allow the RouterModule to activate p only if the user is logged in.
But what happens when p is active and the user gets logged out? I have tried to find best practices on checking if a page is allowed to be active without changing the route in the RouterModule but I can't find anything useful. Lets say page p is active and requires a login. Now a logout is triggered somehow while p is active but no route change is involved. Lets say the server responded with a 401 and the app notices the user is not logged in anymore. What would be the best practice to check if the active page requires a login and take measures accordingly? It could be that the active page does not require a login. In that case everything should remain as it is.
you may add data with your routes, which you may use later to check if authentication is required for that route or not,
something like below,
{
path: ...,
component: ...,
canActivate: [CanActivateGuard],
data: { authRequired: true }
}
in the logout trigger, you can inject ActivatedRoute to check on the activated routes data to determine if you want to send the user to login page or not,
constructor(route: ActivatedRoute) {}
...
someCallBack(){
if(!!this.route.snapshot.data
&& this.route.snapshot.data.authRequired == true){
// redirect to login page
}
}
Hope this helps!!
来源:https://stackoverflow.com/questions/46812955/angular2-trigger-canactivate-while-page-is-active