我在试着检测路由器失活。
以下是路由器的定义:
export const AppRoutes: Routes = [
{
path: '',
component: HelloComponent,
canDeactivate: [ConfirmDeactivateGuard]
},
{
path: 'error',
component: ErrorComponent,
canDeactivate: [ConfirmDeactivateGuard],
},
{
path: '**',
component: ErrorComponent,
canDeactivate: [ConfirmDeactivateGuard],
pathMatch: 'full',
}
];
export const AppRouting: ModuleWithProviders = RouterModule.forRoot(AppRoutes, {
enableTracing: true,
});这是我的停用警卫服务:
@Injectable()
export class ConfirmDeactivateGuard implements CanDeactivate<HelloComponent> {
canDeactivate(target: HelloComponent) {
// This code is never called. Why?
return window.confirm('wtf?' || 'Are you sure?');
}
}当我尝试从根url('/')转到其他url时,我希望看到窗口确认。然而,这种情况并没有发生。你有什么想法吗?你有没有发现什么遗漏的东西?
如果您想联机查看代码,请查看下面的链接:
https://stackblitz.com/edit/angular-vw9b7u?file=src%2Fapp%2FdeactivateGuard.ts
发布于 2018-08-02 11:43:44
您需要将保护添加到模块的提供程序
providers: [ConfirmDeactivateGuard],这是一个改进的stackblitz演示
编辑:这个保护不是从直接导航中触发的,即当您在adressbar中直接输入URL时。保护只触发在角应用程序内的导航(见这里)。您可以使用beforeunload事件作为解决办法。
发布于 2018-08-02 11:43:57
也许,如果你在模块的提供者中提供了保护,并提出了一种导航方法,它就能工作.
https://stackoverflow.com/questions/51652457
复制相似问题