尝试使用下面的代码而不是等待post调用成功,在响应到来之前跳到下一次迭代。要求:在两次api(POST/PATCH)调用成功后需要进行下一次迭代
for (item of data) {
A(item)
}
A(value) {
const resp = this.post(url, {
'rationale': value['rationale']
})
.mergeMap(tempObj => {
value['detail'] = tempObj['id']
return this.patch(url, value['extid'], value)
})
.subscribe()
}发布于 2020-01-17 22:27:23
最近,我在angular http中使用了toPromise函数,将一个观察值变成了一个promise。如果在异步函数中有外部循环,这可能会起作用:
// This must be executed inside an async function
for (item of data) {
await A(item)
}
async A(value) {
const resp = await this.post(url, {
'rationale': value['rationale']
})
.mergeMap(tempObj => {
value['detail'] = tempObj['id']
return this.patch(url, value['extid'], value)
}).toPromise();
}发布于 2020-01-18 19:25:25
使用from发出数组的项。使用concatMap映射到可观察对象,并且仅在前一个对象完成后才映射到下一个对象。
const resp$ = from(data).pipe(
concatMap(value => this.post(url, { 'rationale': value['rationale'] }).pipe(
switchMap(tempObj => {
value['detail'] = tempObj['id']
return this.patch(url, value['extid'], value)
})
))
)我使用switchMap而不是mergeMap来表明没有使用mergeMap同时运行多个可观察对象的特性。
发布于 2020-01-19 01:54:32
您可以使用:
<form (ngSubmit)="submit$.next(form.value)" ...在您的组件中:
submit$= new Subject();
ngOnInit {
submit$.pipe(
exhaustMap(value =>
this.post(url, {'rationale': value.rationale}))
.pipe(concatMap( response => {
value.detail = response.id;
return this.patch(url, value.extid, value);
}))).subscribe(); // rember to handle unsubcribe
}我之所以使用exhaustMap,通常是因为post和path是变异调用,所以运算符确保第一个提交是处理忽略其余部分,同时处理AKA避免双重提交
一个更好的方法是使用ngrx效果,如果你还不知道它,我建议你去学习它。
submit$ = createEffect(
() => this.actions$.pipe(
ofType(FeatureActions.submit),
exhaustMap( ({value}) => // if action has value property
this.post(url, { rationale : value.rationale}))
.pipe(concatMap( response => {
value.detail = response.id;
return this.patch(url, value.extid, value);
})),
map(result => FeatureActions.submitSuccess(result))
)
);https://stackoverflow.com/questions/59789003
复制相似问题