检查用户登录的页面是否在Angular 2中进行了更改 [英] Check if the user logged in on any page change in 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.
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 itsactivate
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: