angular - 如何保護所有路由以防停用 [CanDeactivate]?
我想為所有路由應用停用守衛,並在組件層級保持控制。
所以我有這個抽象類別:
export abstract class Deactivable {
abstract shouldDeactivate(): Observable<boolean> | Promise<boolean> | boolean;
}
這裡是警衛:
export class CanDeactivateService implements CanDeactivate<Component> {
canDeactivate(
component: Component,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState?: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if(component instanceof Deactivable) {
return component.shouldDeactivate();
}
return true;
}
}
然後在元件中我就像這樣(為了簡潔,將 observable 換成 bool):
export class MyComponent extends Deactivable implements... {
///// Deactivable
shouldDeactivate(): boolean {
return false;
}
////////
}
然後我將守衛應用到根路由,但它不起作用,似乎 shouldDeactivate 從未被調用,出了什麼問題?
編輯 1: 事實上,我發現守衛的 canDeactivate 從來沒有被呼叫過……這可能是個錯誤嗎?
編輯 2: 使用方法:
const routes: Routes=[
{ path: "", canDeactivate: [CanDeactivateService], children: [
//All routes here
] }
]