我有一个包含两个部分的表单,它们调度两个后请求操作,第二个请求需要第一个请求中的参数才能成功发送。但我不确定如何:(我有第一个操作的请求和响应工作正常,但我只是不确定如何或在哪里实现逻辑 - 它应该在服务中吗?减速机?我尝试了forkjoin,然后意识到我不知道自己在做什么。提前感谢任何帮助!
我的组件 :
const newArtist = this.store.dispatch(new CreateArtist({
...generalDetails,
hometown,
}))
const newArtistExtraInfo = this.store.dispatch(new CreateDiscography({
...songCatalogue
}
));
forkJoin([newArtist, newArtistExtraInfo]).subscribe(result => {
console.log(`the results are in : ${result}`)
})
如果要使用调度的第一个操作的结果,则很可能希望在处理完CreateArtist
后读取更新的状态。
在组件中,您可以使用一个Selector
返回由ArtistState
处理CreateArtist
产生的最新创建艺术家:
@Select(ArtistState.latestArtist) artist$: Observable<Artist>;
this.store.dispatch(new CreateArtist(..))
.pipe(
withLatestFrom(this.artist$)
)
.subscribe(([_, artistInfo]) => {
this.store.dispatch(new CreateDiscography({ .., artistInfo.token, artistInfo.id });
})
因此,在这里您调度创建艺术家操作,然后在创建后读取状态以获取调度后续唱片操作所需的艺术家特定信息。
另一种选择是,您的状态作为包含您所追求的令牌/IDArtistCreated
操作进行调度,并且您的组件通过操作流订阅该操作,然后它可以在其中调度唱片操作。
在这种情况下,您可以使用 RxJSswitchMap
运算符管道传入第二个请求。尝试以下操作
firstRequest().pipe(
switchMap(responseFirst => secondRequest(responseFirst)),
catchError(errorFirst => of(errorFirst))
).subscribe(
responseSecond => { },
errorSecond => { }
);
现在,第一个请求将完成,它的响应将用作第二个请求的参数。还有其他高阶映射运算符,如mergeMap
、concatMap
和exhaustMap
用于特定目的。
为此,您需要扩展处理CreateArtist
的效果以调度另一个操作。
ofType(actions.CreateArtist),
switchMap(action => this.http.get('url1')),
// this action goes to effects again to its own handler.
map(response => new CreateDiscography(someParams)),