CanActivate:将 Observable<Observable<boolean>> 转换为 Observable<boolean>
CanActivate: Converting Observable<Observable<boolean>> to Observable<boolean>
我有一个只有所有者才能访问的用户设置页面。我想使用 CanActivate 来实现限制。 CanActivate 要求输出为布尔值或布尔值的可观察值。但是,我的代码输出一个布尔值的可观察值。
Type 'Observable<Observable<boolean>>' is not assignable to type 'boolean | Observable<boolean> | Promise<boolean>'.
Here my code
@Injectable()
export class UserGuard implements CanActivate {
constructor(
private route: ActivatedRoute,
private userService: UserService
) { }
canActivate() {
const username = this.route.snapshot.paramMap.get('username');
return this.userService.authState().map(auth => {
return this.userService.getByUid(auth.uid).map(user => {
return user.username === username ? true : false;
});
});
}
}
使用 .switchMap
以展平可观察对象。在此处阅读更多信息:https://www.learnrxjs.io/operators/transformation/switchmap.html
本质上,如果您将 .switchMap
链接到一个源可观察对象并返回一个内部可观察对象,那个 可观察对象将被订阅并发出它的值,而不是可观察对象本身正在发射:
return this.userService.authState().switchMap(auth => {
在这种情况下,您还可以通过将 .map
链接到原始可观察流来稍微扁平化您的代码。
return this.userService.authState().switchMap(auth =>
this.userService.getByUid(auth.uid)
).map(user => user.username === username);
我有一个只有所有者才能访问的用户设置页面。我想使用 CanActivate 来实现限制。 CanActivate 要求输出为布尔值或布尔值的可观察值。但是,我的代码输出一个布尔值的可观察值。
Type 'Observable<Observable<boolean>>' is not assignable to type 'boolean | Observable<boolean> | Promise<boolean>'.
Here my code
@Injectable()
export class UserGuard implements CanActivate {
constructor(
private route: ActivatedRoute,
private userService: UserService
) { }
canActivate() {
const username = this.route.snapshot.paramMap.get('username');
return this.userService.authState().map(auth => {
return this.userService.getByUid(auth.uid).map(user => {
return user.username === username ? true : false;
});
});
}
}
使用 .switchMap
以展平可观察对象。在此处阅读更多信息:https://www.learnrxjs.io/operators/transformation/switchmap.html
本质上,如果您将 .switchMap
链接到一个源可观察对象并返回一个内部可观察对象,那个 可观察对象将被订阅并发出它的值,而不是可观察对象本身正在发射:
return this.userService.authState().switchMap(auth => {
在这种情况下,您还可以通过将 .map
链接到原始可观察流来稍微扁平化您的代码。
return this.userService.authState().switchMap(auth =>
this.userService.getByUid(auth.uid)
).map(user => user.username === username);