Angular2 trigger CanActivate while page is active

人走茶凉 提交于 2019-12-07 07:11:35

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!