如何申请才能开启所有航线的守卫?

问题描述 投票:0回答:3

我有一个 angular2 主动防护,它可以处理用户未登录的情况,将其重定向到登录页面:

import { Injectable } from  "@angular/core";
import { CanActivate , ActivatedRouteSnapshot, RouterStateSnapshot, Router} from "@angular/router";
import {Observable} from "rxjs";
import {TokenService} from "./token.service";

@Injectable()
export class AuthenticationGuard implements CanActivate {

    constructor (
        private router : Router,
        private token : TokenService
    ) { }

    /**
     * Check if the user is logged in before calling http
     *
     * @param route
     * @param state
     * @returns {boolean}
     */
    canActivate (
        route : ActivatedRouteSnapshot,
        state : RouterStateSnapshot
    ): Observable<boolean> | Promise<boolean> | boolean {
        if(this.token.isLoggedIn()){
            return true;
        }
        this.router.navigate(['/login'],{ queryParams: { returnUrl: state.url }});
        return;
    }
}

我必须在每条路线上实施它,例如:

const routes: Routes = [
    { path : '', component: UsersListComponent, canActivate:[AuthenticationGuard] },
    { path : 'add', component : AddComponent, canActivate:[AuthenticationGuard]},
    { path : ':id', component: UserShowComponent },
    { path : 'delete/:id', component : DeleteComponent, canActivate:[AuthenticationGuard] },
    { path : 'ban/:id', component : BanComponent, canActivate:[AuthenticationGuard] },
    { path : 'edit/:id', component : EditComponent, canActivate:[AuthenticationGuard] }
];

有没有更好的方法来实现 canActive 选项而不将其添加到每个路径。

我想要的是将其添加到主路线上,并且它应该适用于所有其他路线。我搜索了很多,但找不到任何有用的解决方案。

angular typescript angular-routing
3个回答
236
投票

您可以引入无组件父路由并在那里应用守卫:

const routes: Routes = [
    {path: '', canActivate:[AuthenticationGuard], children: [
      { path : '', component: UsersListComponent },
      { path : 'add', component : AddComponent},
      { path : ':id', component: UserShowComponent },
      { path : 'delete/:id', component : DeleteComponent },
      { path : 'ban/:id', component : BanComponent },
      { path : 'edit/:id', component : EditComponent }
    ]}
];

19
投票

您还可以在 app.component 的 ngOnInit 函数中订阅路由器的路由更改,并从那里检查身份验证,例如

    this.router.events.subscribe(event => {
        if (event instanceof NavigationStart && !this.token.isLoggedIn()) {
            this.router.navigate(['/login'],{ queryParams: { returnUrl: state.url}}); 
        }
    });

我更喜欢这种在路线更改时进行任何类型的应用程序范围检查的方式。


3
投票

我认为你应该实现“子路由”,它允许你有一个父母(例如路径“admin”)和他的孩子。

然后您可以向父级应用 canactivate ,这将自动限制对其所有子级的访问。例如,如果我想访问“admin/home”,我需要通过 canActivate 保护的“admin”。如果需要,您甚至可以使用空路径“”定义父级

© www.soinside.com 2019 - 2024. All rights reserved.