【发布时间】:2017-05-24 14:28:10
【问题描述】:
在下面的代码中,我有一个 User 对象,它可以有可变数量的帐户 ID 与之关联。当用户更新时,应为用户对象中包含的每个帐户发出额外的请求:
class User {
id: number;
accountIds: Array<number>;
}
// Side effects class
@Effect()
update$ = this.actions$
.ofType('USER_UPDATE')
.switchMap(action => {
let user = action.payload;
for (let accountId of user.accountIds) {
let account = { id: accountId, userIds: [user.id] };
// Is there any way to chain these api calls with switch maps
// and then finally switch map to the user request below?
return this.apiService.post(`/accounts/${account.id}`, account);
}
return this.apiService.post(`/users/${userid}`, user);
}
有没有办法使用 RxJS 使用 switchMap(或类似的东西)将这些调用链接在一起,这样 observable 才被认为是完整的直到所有后续请求都完成而无需编写一些一种自定义的递归逻辑?
【问题讨论】:
-
也许您想使用
Observable.forkJoin(如果顺序无关紧要)...将所有请求存储在Array中并像这样使用:Observable.forkJoin(<myRequestsArray>)... -
是的,我看到了 forkJoin,似乎并行发送所有请求,这不是我所追求的,但看起来是迄今为止最好的方法。谢谢。
-
这些链接很好,谢谢@martin
标签: angular rxjs angular-http