在 Angular 中,如何将我的 post 请求的响应作为参数之一传递到另一个 post 请求中?



我有一个包含两个部分的表单,它们调度两个后请求操作,第二个请求需要第一个请求中的参数才能成功发送。但我不确定如何:(我有第一个操作的请求和响应工作正常,但我只是不确定如何或在哪里实现逻辑 - 它应该在服务中吗?减速机?我尝试了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 => { }
);

现在,第一个请求将完成,它的响应将用作第二个请求的参数。还有其他高阶映射运算符,如mergeMapconcatMapexhaustMap用于特定目的。

为此,您需要扩展处理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)),

最新更新