【问题标题】:How to apply canActivate guard on all the routes?如何在所有路由上应用 canActivate 保护?
【发布时间】:2017-09-15 05:12:06
【问题描述】:

我有一个 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


    【解决方案1】:

    你可以引入一个无组件的父路由并在那里应用防护:

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

    【讨论】:

    • 很高兴听到 :) 感谢您的反馈。
    • @GünterZöchbauer 我总是阅读您的建议。非常感谢!!但就我而言,这不起作用。 CanActive 在子节点之间的路由中不起作用。我使用 canActivateChild。它有效。
    • 很高兴听到您发现我的回答很有帮助 :) 并感谢您提及 canActivateChild
    • 我不确定。你可以试试canActivateChild 而不是canActivate。我自己还没用过。
    • 是的,canActivateChild 对于给定的场景来说是一种更好的方法来封装所有子路由。并且父级本身可以使用canActivatecanLoad 进行保护,具体取决于它在应用程序中加载的时间。此外,代码 sn-p 将在 v6.0 中给出控制台错误,因为 Angular 将期望路由配置中的组件或子声明。
    【解决方案2】:

    我认为您应该实现“子路由”,它允许您拥有父级(例如,路径为“admin”)和他的子级。

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

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

      • 如何用这种方法得到state.url
      猜你喜欢
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      相关资源
      最近更新 更多