检查用户是否登录了 Angular 2 中的任何页面更改 [英] Check if the user logged in on any page change in Angular 2

查看:11
本文介绍了检查用户是否登录了 Angular 2 中的任何页面更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular2 的进展缓慢但肯定.现在我面临以下挑战.我想检查用户是否在每个页面更改时登录(换句话说,在每个组件的负载上).当然,我可以在每一个中实现 OnInit 接口,但那是代码味道.

Slowly but surely progressing with Angular2. And now I faced the following challenge. I want to check if the user logged in or not on every page change (in other words on load of each and every component). Of course, I can implement OnInit interface in each and every one of them, but that is code smell.

是否有任何有效的方法可以在应用程序的每个页面上执行所需的任何内容?我很想听听有关如何处理此任务的最佳实践的任何其他建议.

Is there any efficient way of executing anything that needed on every page of the app? I would love to hear any other suggestions about best practices of how to handle this task.

我正在使用这个库(https://auth0.com/blog/2015/11/10/introducing-angular2-jwt-a-library-for-angular2-authentication/) 用于基于 jwt 的登录,我已经有了一个不错的封装所有身份验证相关功能的服务类.因此,实际检查用户登录或未登录的位置已经完成并经过测试.

I am using this library (https://auth0.com/blog/2015/11/10/introducing-angular2-jwt-a-library-for-angular2-authentication/) for jwt based login and I already have a nice service class that encapsulates all authentication related functionality. So, the actual checking where or not the user is logged in is already done and tested.

谢谢,

推荐答案

如果您使用路由(而且似乎是这样,因为您说:在每次页面更改时"),您可以利用几件事:

If you use routing (and it seems to be the case since you say: "on every page change"), you can leverage several things:

  • 创建一个自定义路由器出口(RouterOutlet 的子类),调用其 activate 方法检查身份验证.在这种情况下,你可以拥有一些全局的东西.类似的东西:

  • Create a custom router-outlet (a sub class of RouterOutlet) that checks authentication with its activate method is called. In this case, you can have something global. Something like that:

@Directive({
  selector: 'auth-outlet'
})
export class AuthOutlet extends RouterOutlet {
  (...)

  activate(oldInstruction: ComponentInstruction) {
    var url = this.parentRouter.lastNavigationAttempt;
    if (isAuthenticated()) {
      return super.activate(oldInstruction);
    } else {
      (...)
    }
  }
}

查看这个问题了解更多详情:

See this question for more details:

利用 CanActivate 装饰器检查组件是否可以激活.在您的情况下,您可以在此级别执行身份验证检查.

Leverage the CanActivate decorator to check is a component can be activated or not. In your case, you can execute authentication checking at this level.

还可以在 RouterLink 级别执行某些操作来显示/隐藏路由链接.在这种情况下,您可以根据相关路由配置和当前用户提示在这些链接上应用角色.有关详细信息,请参阅此问题:

Something could also be done at the RouterLink level to show / hide route links. In this case, you can apply roles on these links based on related route configuration and current user hints. See this question for more details:

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