【问题标题】:Protected Router Outlet in new Router-angular2新 Router-angular2 中受保护的路由器插座
【发布时间】:2016-09-01 05:36:02
【问题描述】:

您好,在已弃用的 ng2 路由中,我使用了一个受保护的插座,它仅在用户通过身份验证时才导航到组件。但在新路由器中,我没有找到任何人谈论受保护的路由。每个人在定义他们的路由时都在使用 canActivate 保护在app.routing.ts 文件中。我觉得与其在我的路由定义中为路由定义 canActivate 保护,不如使用一个受保护的插座似乎是一种简单的方法。

@Directive({
selector: 'protected-router-outlet',
})
export class ProtectedOutlet extends RouterOutlet {
private parentRouter: Router;
publicRoutes: any;
constructor(_viewContainer: ViewContainerRef, _loader: DynamicComponentLoader, _parentRouter: Router, @Attribute('name') nameAttr: string, private auth: AuthService) {
    super(_viewContainer, _loader, _parentRouter, nameAttr);

    this.parentRouter = _parentRouter;
    this.publicRoutes = {
        '/Login': true
    };
}
  activate(instruction: ComponentInstruction) {
    var url = this.parentRouter.lastNavigationAttempt;
    var LoggedIn = this.auth.IsLoggedIn();
    if (!LoggedIn) {
        this.parentRouter.navigateByUrl('/Login');
    }
    return super.activate(instruction);
  }
}

是否有可能在新路由器中有一个受保护的插座。如果是,我如何使用受保护的插座,因为我在新路由中找不到ComponentInstruction。 有人可以帮助我。如果我错了,请建议我用正确的方法来保护路线。谢谢

【问题讨论】:

  • 为什么要避开CanActivate守卫?
  • 因为我应该为每个定义的路线定义。我不反对CanActivate。但不是定义canActivate,我认为保护插座很容易使用。即使我忘记提及canActivate,受保护的插座也能处理

标签: angular


【解决方案1】:

如果为每条路由指定 AuthGuard 太麻烦,可以这样做:

const unprotectedRoutes = [];
const protectedRoutes = [
  // protected routes here
].map((r:Route) => {
  r.canActivate = (r.canActivate) ? [AuthGuard, ...r.canActivate] : [AuthGuard];
  return r;
});

export const routeConfig = [...unprotectedRoutes, ...protectedRoutes];

我正在使用它为我的所有路线添加一个“LogGuard”(它实际上并不保护任何东西,而是记录导航)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-29
    • 2020-10-26
    • 2022-07-30
    • 2022-11-27
    • 1970-01-01
    • 2017-03-21
    • 2018-08-11
    • 1970-01-01
    相关资源
    最近更新 更多