如何保护所有停用的路由[CanDeactivate]?

时间:2018-12-12 17:43:23

标签: angular typescript routing

我想对所有路由应用停用保护措施,并将控制权保持在组件级别。

所以我有这个抽象类:

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;
  }

}

,然后在我喜欢的组件中(为简洁起见,可以将其替换为bool):

export class MyComponent extends Deactivable implements... {

  ///// Deactivable
  shouldDeactivate(): boolean {
    return false;
  }
  ////////
}

然后我将保护应用于根路由,但是它不起作用,似乎应该永远不会调用Deactivate,这是怎么回事?

修改1: 实际上,我发现后卫的canDeactivate从未被调用过... 可能是错误吗?

修改2: 用法:

const routes: Routes=[
    { path: "", canDeactivate: [CanDeactivateService], children: [
        //All routes here
    ] }
]

0 个答案:

没有答案