Angular CanDeactivate不起作用
我正在尝试检测路由器停用 以下是路由器的定义:Angular CanDeactivate不起作用,angular,routing,Angular,Routing,我正在尝试检测路由器停用 以下是路由器的定义: export const AppRoutes: Routes = [ { path: '', component: HelloComponent, canDeactivate: [ConfirmDeactivateGuard] }, { path: 'error', component: ErrorComponent, canDeactivate: [ConfirmDeactivateGu
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?');
}
}
@Injectable()
导出类ConfirmDeactivateGuard实现CanDeactivate{
canDeactivate(目标:HelloComponent){
//这个代码从未被调用。为什么?
返回窗口。确认('wtf?'| |'确定吗?');
}
}
当我尝试从根url(“/”)转到其他url时,我希望看到窗口确认。然而,这并没有发生。你有什么想法吗?或者你发现有什么遗漏了吗
如果您想在线查看代码,请查看以下链接:
您需要将防护添加到模块的提供程序中
providers: [ConfirmDeactivateGuard],
这是一个
编辑:当您直接在地址栏中键入URL时,直接导航不会触发该防护。仅当angular应用程序内导航时才会触发中的防护(请参阅)。您可以在卸载前使用
事件作为解决方法如果您在模块的提供程序中提供了保护并提出了一种导航方式,那么它可能会起作用
您是对的,提供商失踪了。但是,如果我们想更改地址栏上的url,它仍然不起作用。@ankakusu我编辑了我的答案。如果您还希望收到地址栏导航的通知,则guard不是正确的选项