【发布时间】:2021-12-31 05:10:33
【问题描述】:
结帐this 回答以了解该方法。我正在使用相同的解决方案来实现主守卫,因为我有多个守卫并希望按顺序执行它们。
在大师卫队中 -
return guard.canActivate(this.route, this.state);
整个函数如下:
//Create an instance of the guard and fire canActivate method returning a promise
private activateGuard(guardKey: string): Promise<boolean> {
let guard: Guard1 | Guard2 | Guard3 | Guard4;
switch (guardKey) {
case GUARDS.GUARD1:
guard = new Guard1();
break;
case GUARDS.GUARD2:
guard = new Guard2();
break;
case GUARDS.GUARD3:
guard = new Guard3();
break;
case GUARDS.GUARD4:
guard = new Guard4(this._Guard4DependencyService);
break;
default:
break;
}
return guard.canActivate(this.route, this.state);
}
我收到下面提到的错误:
Type 'boolean | Observable<boolean>' is not assignable to type 'boolean'.
Type 'Observable<boolean>' is not assignable to type 'boolean'.
请找到stackblitz 链接
【问题讨论】:
-
如果guard.canActivate() 返回布尔值,您可以简单地将返回类型添加为布尔值。
private activateGuard(guardKey: string): Promise<boolean> | boolean -
嗨@DevangPatel 我尝试了你的建议,但错误仍然存在:键入'boolean |承诺
| Observable ' 不可分配给类型 'boolean |承诺'。类型 'Observable ' 不可分配给类型 'boolean |承诺'。类型 'Observable ' 缺少类型 'Promise ' 的以下属性:然后,catch,finally,[Symbol.toStringTag] -
你能在 stackblitz 上分享代码吗?
-
@DevangPatel: stackblitz.com/edit/angular-route-guards-zkcvpm?file=src/app/… 也在问题中添加
-
只需将函数的返回类型更改为
boolean | Promise<boolean>,Angular Guards 两者都接受。
标签: angular typescript angular-ui-router