Angular2 在页面处于活动状态时触发 CanActivate [英] Angular2 trigger CanActivate while page is active

查看:23
本文介绍了Angular2 在页面处于活动状态时触发 CanActivate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,Angular2 中的 CanActivate 接口仅对路由更改有效.因此,如果我有一个页面 p 需要用户登录,我可以创建一个实现 CanActivate 接口的保护,该接口将允许 RouterModule 仅在用户登录时激活p.

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.

但是当 p 处于活动状态并且用户被注销时会发生什么?我试图找到检查页面是否允许在不更改 RouterModule 中的路由的情况下处于活动状态的最佳实践,但我找不到任何有用的东西.假设页面 p 处于活动状态并且需要登录.现在,当 p 处于活动状态时会以某种方式触发注销,但不涉及路由更改.假设服务器以 401 响应,应用程序通知用户不再登录.检查活动页面是否需要登录并采取相应措施的最佳做法是什么?可能是活动页面不需要登录.在这种情况下,一切都应该保持原样.

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.

推荐答案

您可以将 data 添加到您的路由中,您可以稍后使用它来检查该路由是否需要身份验证,

you may add data with your routes, which you may use later to check if authentication is required for that route or not,

如下所示,

{
  path: ..., 
  component: ..., 
  canActivate: [CanActivateGuard], 
  data: { authRequired: true }
}

在注销触发器中,您可以注入ActivatedRoute来检查激活的路由数据,以确定是否要将用户发送到登录页面,

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

  }
}

这篇关于Angular2 在页面处于活动状态时触发 CanActivate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆