如何在所有路线上应用canActivate Guard? [英] How to apply canActivate guard on all the routes?

查看:130
本文介绍了如何在所有路线上应用canActivate Guard?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个angular2主动防护,如果用户未登录,它将进行处理,将其重定向到登录页面:

I have a angular2 active guard which handle if the user is not logged in, redirect it to login page:

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;
    }
}

我必须在每条路线上都实现它:

I have to implement it on each route like :

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选项而不将其添加到每个路径中?

Is there any better way to implement canActive option without adding it to each path.

我要在主路由上添加它,并且它应该应用于所有其他路由.我已经搜索了很多,但是找不到任何有用的解决方案

What I want is to add it on main route, and it should apply to all other routes. I have searched alot, but I could not find any useful solution

谢谢

推荐答案

您可以引入无组件的父路由并在此处应用防护措施:

You can introduce a componentless parent route and apply the guard there:

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 }
    ]}
];

这篇关于如何在所有路线上应用canActivate Guard?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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