首页 文章

如何在所有路线上申请canActivate后卫?

提问于
浏览
36

我有一个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选项而不将其添加到每个路径 .

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

谢谢

4 回答

  • 4

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

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

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

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

    当路线改变时,我更喜欢这种方式进行任何类型的应用程序检查 .

  • 85

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

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

  • 0

    我在搜索时遇到了这个例子,并被示例中给出的示例所捕获 .

    如果要显示子路径,则需要确保警卫返回true .

    @Injectable()
    export class AuthenticationGuard implements CanActivate {
    
        constructor(
            private router: Router,
            private authService: AuthService) { }
    
        canActivate(
            route: ActivatedRouteSnapshot,
            state: RouterStateSnapshot
        ): Observable<boolean> | Promise<boolean> | boolean {
    
            // Auth checking code here
    
            // Make sure you return true here if you want to show child routes
            return true;
        }
    }
    

相关问题