我对rxjs操作符有点困惑。我有几个返回可观察的api调用:
getCurrentUser(): Observable<any> {
return this.http.get<any>(userUrl);
}
tagsList(): Observable<string[]> {
return this.http.get<string[]>(tagsUrl);
}
timezonesList(): Observable<Timezone[]> {
return this.http.get<Timezone[]>(timezonesUrl);
}我想调用getCurrentUser(),然后返回值调用操作LoadUser(user)的结果,然后在用户加载之后,同时调用多个异步请求:
tagsList(), timezonesList()然后用它们的返回值结果调用actions LoadTags(tags), LoadTimezones(timezones)
所以应该是这样的:
init() {
this.accountsApi.getCurrentUser()
.map((user: User) => this.store.dispatch(new LoadUser({ user })))
.map(
this.commonApi.tagsList(),
this.commonApi.timezonesList(),
this.commonApi.authoriztionServicesList()
)
.map((tags, timezones, authorizationServices) => {
this.store.dispatch(new tagsActions.LoadTags(tags));
this.store.dispatch(new timezonesActions.LoadTimezones(timezones));
this.store.dispatch(new authorizationServicesActions.LoadAuthorizationServices(authorizationServices));
});
}我知道这个操作员是错的。我应该用什么操作员来处理这个问题?我已经做了承诺,但我相信我可以用rxjs操作符在较少的代码行。
这对我来说也很有趣,我怎么能用异步/等待来完成这个任务呢?谢谢
发布于 2018-05-15 15:00:26
在您的原始代码中,您使用map有点过了,对于一些您可能不需要映射的用例。
init() {
return this.accountsApi.getCurrentUser()
.do((user: User) => this.store.dispatch(new LoadUser({ user })))
.forkJoin(
this.commonApi.tagsList(),
this.commonApi.timezonesList(),
this.commonApi.authoriztionServicesList()
)
.do((results) => {
this.store.dispatch(new tagsActions.LoadTags(results[0]));
this.store.dispatch(new timezonesActions.LoadTimezones(results[1]));
this.store.dispatch(new authorizationServicesActions.LoadAuthorizationServices(results[2]));
});
}forkJoin允许您启动许多可观察的订阅,一旦所有订阅生成值,您就可以得到一个可观察值的数组。
do操作符引入了启动存储操作的副作用,因为您不想创建任何数组。
https://stackoverflow.com/questions/50353350
复制相似问题