在Angular 4中,可以使用CanDeactivate
路由守卫来控制是否允许离开当前页面。如果你的CanDeactivate
路由守卫没有起作用,可以尝试以下解决方法:
canDeactivate
属性来指定CanDeactivate
路由守卫。例如:import { CanDeactivate } from '@angular/router';
export class YourComponent implements CanDeactivate {
canDeactivate() {
// 添加你的逻辑来判断是否允许离开当前页面
}
}
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'your-path',
component: YourComponent,
canDeactivate: [YourComponent]
}
])
],
exports: [RouterModule]
})
export class AppRoutingModule { }
CanDeactivate
接口,并在组件中实现canDeactivate
方法。在canDeactivate
方法中,你可以添加逻辑来判断是否允许离开当前页面。例如:import { CanDeactivate } from '@angular/router';
export class YourComponent implements CanDeactivate {
canDeactivate() {
// 添加你的逻辑来判断是否允许离开当前页面
}
}
Observable
或Promise
来表示是否允许离开当前页面。例如:import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';
export class YourComponent implements CanDeactivate {
canDeactivate(): Observable | Promise | boolean {
// 添加你的逻辑来判断是否允许离开当前页面
}
}
CanDeactivate
路由守卫。例如:import { CanDeactivate } from '@angular/router';
import { YourComponent } from './your-component.component';
@NgModule({
// ...
providers: [
YourComponent,
CanDeactivateGuard
]
})
export class YourModule { }
以上是一些可能导致CanDeactivate
路由守卫不起作用的常见问题和解决方法。根据你的具体情况,你可能需要进一步调试和排查问题。