我有一个只有所有者才能访问的用户设置页面。我想使用CanActivate来实现这个限制。CanActivate要求输出为布尔值或布尔值的可观测值。但是,我的代码输出了一个可观察的布尔值。
Type 'Observable<Observable<boolean>>' is not assignable to type 'boolean | Observable<boolean> | Promise<boolean>'.这是我的代码
@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;
});
});
}
}发布于 2017-11-15 20:58:29
使用.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);https://stackoverflow.com/questions/47317019
复制相似问题