带有子路由的 Angular 2 身份验证 [英] Angular 2 Authentication with child routes

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

问题描述

我有一个 angular 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);
      }
   }
}

这是一个工作代码: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?

推荐答案

对于发现这一点的任何人,现在在 Angular 2 中的答案是使用Guards"作为新路由器的一部分.请参阅 Angular 2 文档:

For anyone that finds this, the answer now in Angular 2 is to use "Guards" as part of the new Router. See Angular 2 documentation:

https://angular.io/docs/ts/latest/guide/router.html#!#guards

一个基本的守卫只是实现了CanActivate",并且可以如下工作:

A basic guard just implements "CanActivate", and could work as follows:

import {Injectable} from "@angular/core";
import {CanActivate, Router} from "@angular/router";
import {AuthService} from "../services/auth.service";

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private authService:AuthService, private router:Router){}

    canActivate(){
        if(this.authService.isAuthenticated())
            return true;

        this.router.navigate(["/login"]);
        return false;
    }
}

正如你在这个例子中看到的,我有一个 AuthService 在其他地方运行(实现并不重要),它可以告诉守卫用户是否已经通过身份验证.如果有,返回 true,导航照常进行.如果没有,我们返回 false 并将它们重定向到登录屏幕.

As you can see in this example I have an AuthService running somewhere else (implementation isn't important) which can tell the guard if the user has been authenticated. If they have, return true and the navigation happens as usual. If they have not, we return false and redirect them to the login screen.

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

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