在 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/