[英]Return Observable From Result Of Observable
I am very new to RxJS, so I'm not quite sure what question I should be asking here. 我是RxJS的新手,所以我不太确定我应该在这里问什么问题。 I have a service that returns an Observable boolean:
我有一个返回Observable布尔值的服务:
@Injectable
export class UserService {
private isLoggedInSubject = new ReplaySubject<boolean>(1);
public isLoggedIn = this.isLoggedInSubject.asObservable();
}
In an Angular 6 route guard I passing on that value to prevent access to a route: 在Angular 6路由防护中,我传递了该值以防止访问路由:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.userService.isLoggedIn.pipe(take(1));
}
How can I take this value, and return an Observable based on the result? 如何获取该值,并根据结果返回一个Observable? I have tried multiple variations of something like this, but seem to be missing some fundamental concept as this has to be a fairly common thing.
我已经尝试过类似这样的多种变体,但是似乎缺少一些基本概念,因为这是相当普遍的事情。
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
const isLoggedIn = this.userService.isLoggedIn.pipe(take(1));
return isLoggedIn.[???something????](x => {
if (x) {
console.log('is logged in');
return Observable.of(true);
} else {
console.log('is not logged in ');
return Observable.of(false);
}
});
}
You just chain it with more operators: 您只需将其与更多运算符链接在一起:
return this.userService.isLoggedIn.pipe(
take(1),
concatMap(x => {
if (x) {
console.log('is logged in');
return Observable.of(true);
} else {
console.log('is not logged in ');
return Observable.of(false);
})
},
);
Btw, you don't even need to be returning Observable.of
. 顺便说一句,您甚至不需要返回
Observable.of
。 You can use just map
and return eg. 您可以只使用
map
并返回例如。 false
. false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.