typescript - ngrx 效果 - 结合两个 API
问题描述
我有以下效果使用update
api更新对象的一部分,然后我通过api获取整个对象findById
,所以我曾经forkJoin
将这两个api结合起来,但我希望findById
api在api的1秒后执行update
,所以我用过 delay(1000)
,但它不工作
@Effect()
updateGeographicScope$ = this.actions$.pipe(
ofType<conventionsActions.PatchGeographicScope>(conventionsActions.ConventionActionTypes.PATCH_GEOGRAPHIC_SCOPE),
map(action => action.payload),
exhaustMap(geographicScope => forkJoin(this.apiConvention.update(geographicScope),
this.apiConvention.findById (geographicScope.externalId).pipe(delay(1000))).pipe(
map(([first, convention]) => new conventionsActions.PatchSuccess({
id: convention.externalId,
changes: convention
})),
catchError(err => {
console.error(err.message);
return of(new conventionsActions.Failure({ concern: 'PATCH', error: err }));
})
))
);
解决方案
您需要为此使用concat
and timer
。有了concat
它,在开始下一个流之前完成第一个流。所以它进行更新,然后等待 1 秒,然后进行 findById。
@Effect()
updateGeographicScope$ = this.actions$.pipe(
ofType<conventionsActions.PatchGeographicScope>(conventionsActions.ConventionActionTypes.PATCH_GEOGRAPHIC_SCOPE),
map(action => action.payload),
mergeMap(geographicScope => concat(
this.apiConvention.update(geographicScope).pipe(switchMapTo(EMPTY)), // makes a request
timer(1000).pipe(switchMapTo(EMPTY)), // waits 1 sec
this.apiConvention.findById(geographicScope.externalId), // makes a request
)),
map(convention => new conventionsActions.PatchSuccess({
id: convention.externalId,
changes: convention
})),
catchError(err => {
console.error(err.message);
return of(new conventionsActions.Failure({ concern: 'PATCH', error: err }));
}),
repeat(), // make active after a failure
)),
);