对于上下文,我在一个角度路径上有两个守卫,但我不能让他们两个都在路径canActivate上,因为在一个路径上有副作用,而且事实上所有的守卫都会在一条路径上被检查。
因此,为了解决这个问题,我有一个守卫,在特定情况下将其他守卫称为canActivate:
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
return this.service.state$.pipe(
filter((s) => s.updatedFromServer),
switchMap((s) => {
if (/* a condition that means this guard is satisfied */) {
return this.otherGuard.canActivate(next, state);
} else {
return false;
}
})
);另一个guard的canActivate返回类型也是Observable<boolean> | Promise<boolean> | boolean,同样可以返回实际的布尔值或Observable。
TS错误投诉现在是:
Type 'false | Observable<boolean>' is not assignable to type 'ObservableInput<any>'.
Type 'false' is not assignable to type 'ObservableInput<any>'如果另一个防护只返回一个可观察对象,并且这里的switchmap返回也被更改为of(false),那么看起来没问题,但我更喜欢保留可以返回已解析的布尔值的canActivate签名-我只是不知道如何在rxjs映射的上下文中做到这一点。
发布于 2020-09-02 17:08:38
您可以使用isObservable和isPromise检查结果是可观察的还是承诺的。如果不是,则使用of对该值进行包装。
import { isObservable } from 'rxjs';
import { isPromise } from 'rxjs/internal-compatibility';
return this.service.state$.pipe(
filter((s) => s.updatedFromServer),
switchMap((s) => {
let result: any;
if (/* a condition that means this guard is satisfied */) {
result = this.otherGuard.canActivate(next, state);
} else {
result = false;
}
return isObservable(result) || isPromise(result) ? result : of(result)
})
);https://stackoverflow.com/questions/63696863
复制相似问题