角2认证与子路由 [英] Angular 2 Authentication with child routes

查看:183
本文介绍了角2认证与子路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个角2应用程序中,我需要在每一页上进行身份验证。所以,我实现了自定义RouterOutlet确认我登录在每一页的变化。

I have an angular 2 application in which I need to be authenticated on every page. So I have implemented a custom RouterOutlet to confirm I am logged in on every page change.

@Directive({
   selector: 'auth-outlet'
})
export class AuthOutlet extends RouterOutlet {
   publicRoutes: any;
   private parentRouter: Router;
   private authService: AuthService;
   constructor(_elementRef: ElementRef, 
               _loader: DynamicComponentLoader, 
               _parentRouter: Router,
               @Attribute('name') nameAttr: string, 
               _authService: AuthService) {

      super(_elementRef, _loader, _parentRouter, nameAttr);
      this.parentRouter = _parentRouter;
      this.authService = _authService;
      this.publicRoutes = {
          'Login': true
      };
  }

  activate(oldInstruction: ComponentInstruction) {
      var url = this.parentRouter.lastNavigationAttempt;
      console.log('attemping to nav');
      if (!this.publicRoutes[url] && !this.authService.loggedIn){
          var newInstruction = new ComponentInstruction('Login', [], new RouteData(), Login, false, 1);
          return super.activate(newInstruction);
      } else {
          return super.activate(oldInstruction);
      }
   }
}

下面是一个工作code:
<一href=\"http://plnkr.co/edit/YnQv7Mh9Lxc0l0dgAo7B?p=$p$pview\">http://plnkr.co/edit/YnQv7Mh9Lxc0l0dgAo7B?p=$p$pview

Here is a working code: http://plnkr.co/edit/YnQv7Mh9Lxc0l0dgAo7B?p=preview

有没有更好的办法拦截路线的变化和重定向登录时,用户没有通过验证?

Is there a better way to intercept route changes and redirect for login when the user is not authenticated?

推荐答案

您也可以使用的 CanActivate ,但是直销DI是不是此刻的支持。这里是一个不错的解决方法寿。

祝你好运。

这篇关于角2认证与子路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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