Angular 2 : How to have the same guard for multiple components

标签 angular angular2-routing

在 Angular2 中,是否可以将相同的保护(例如 CanActivate 或 CanDeactivate)应用于多个组件?

这是MyComponent1的守卫:

@Injectable()
export class MyGuard implements CanDeactivate<MyComponent1> {

  canDeactivate(component: MyComponent1): Promise<boolean> {
    // my code here
  }
}

我想要为 MyComponent2 提供完全相同的守卫, MyComponent3等等。

我该如何实现?我需要按组件声明一个新的保护类,或者我可以重用我的类 MyGuard ?

最佳答案

只需将相同的守卫添加到您希望应用它的每条路线即可。

或者,您也可以创建一个无组件的父路由,在其中添加防护,所有子路由都将受到同一个防护的保护。
这仅在组件都在同级路由中时才有效。

Angular DI 不支持泛型类型参数。作为一种解决方法,这应该做你想做的事情(尽管事件可能比你想要的更冗长):

routes: [
  { path: 'x', component: MyComponent1, canDeactivate: [new Inject('CanDeactivateMyComponent1') },
  { path: 'y', component: MyComponent2, canDeactivate: [new Inject('CanDeactivateMyComponent2') },

]


@NgModule({
  providers: [
    {provide: 'CanDeactivateMyComponent1', useFactory: () => new CanDeactivate<MyComponent1>()},
    {provide: 'CanDeactivateMyComponent2', useFactory: () => new CanDeactivate<MyComponent2>()},

  ],
})
export class AppModule {}
  ...
})

关于 Angular 2 : How to have the same guard for multiple components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41874283/

相关文章:

javascript - 在 Angular 2 的扩展 RouterOutlet 中导入自定义服务以进行身份​​验证

angular - 我如何导航到兄弟路线?

angular2-routing - 如何在不导航到路由的情况下更改 Angular2 路由参数?

angular - 路由到另一个组件后,服务返回时通知用户

html - 如何触发点击组件中的 HTML 文件元素? ( Angular 2)

Angular 6 错误显示为 'mat-form-field' 不是已知元素 :

css - Angular2如何在拖放时更改背景颜色

Angular 7 CDK 门户 : Error Must provide a portal to attach

typescript - Angular2 Router - 任何人都知道如何在 app.ts 中使用 canActivate 以便我可以在未登录时重定向到主页

javascript - Angular 2如何从innerHTML执行脚本标签