等待RxJS操作-阻止? [英] Wait for RxJS operation - to blocking?
问题描述
我正在使用Angular 4.3.5.我们的应用程序具有可以订阅"用户的程序".我有一个路由器防护功能,如下所示:
I am using Angular 4.3.5. Our app has "programs" that a user can be "subscribed" to. I have a router guard function that looks like this:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const programName = route.params['program_name'];
const programId = this.programService.getIdForName(programName);
if (this.userService.isLoggedIn() && this.subscriptionService.isSubscribed(programId)) {
return true;
} else {
this.router.navigate(['']);
return false;
}
}
要获取程序ID,我需要调用服务器.要获取用户的订阅列表并确定他们是否已订阅此特定程序,我需要调用服务器.
To get the program id, I need to call the server. To get the list of subscriptions for the user and determine if they are subscribed to this particular program, I need to call the server.
使用RxJS进行服务器调用是异步的.但是,我的 canActivate
函数被约束为返回布尔值.我不确定如何弥合这种异步/同步编程差距.
The server calls are asynchronous using RxJS. However, my canActivate
function is constrained to return a boolean. I am unsure of how to bridge this async/sync programming gap.
例如,在RxJava中,我可以调用 toBlocking()
以等待HTTP调用解决.但是RxJS中没有这样的运算符.我已经尝试过 toArray()
和 take(1).toArray()[0]
,但是似乎没有任何作用.
In RxJava, for example, I could call toBlocking()
to wait for the HTTP call to resolve. But there is no such operator in RxJS. I've tried toArray()
, and take(1).toArray()[0]
, but nothing seems to work.
事实上,我想将这个异步/同步桥降低一些;即我希望 subscriptionService.isSubscribed(programId)
返回一个 boolean
而不是一个 Observable< boolean>
,因为我可以缓存订阅列表在 SubscriptionService
中,这样我就不需要每次都调用服务器了;但我认为这不会改变编程的挑战.
In fact, I'd like to push this async/sync bridge down lower; i.e. I want subscriptionService.isSubscribed(programId)
to return a boolean
instead of a Observable<boolean>
, because I can cache the list of subscriptions in the SubscriptionService
, so that I don't need to call the server every time; but I don't think that changes the programming challenge.
推荐答案
canActivate
函数可以返回 Observable< boolean>
.
这篇关于等待RxJS操作-阻止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!