問題描述
發送 forkjoin api,每個 api 之間有延遲 (Send forkjoin api with a delay in between each api)
我目前正在處理一個 Angular 項目,我必須使用 forkjoin 以 ngrx 效果發送多個 api。這有一個問題,我必須延遲發送多個 api,就好像我一次發送一樣,它們被取消了。我的調用效果如下所示:
@Effect()
timeslot$ = this.actions$
.ofType(a.ItemActionTypes.GET_TIME_SLOTS)
.map((action: a.GetTimeSlots) => action.payload)
.switchMap(payload => {
const serviceCol = payload.map(pl => this.service.getTimeSlots(pl));
return Observable.forkJoin(serviceCol).pipe(
mergeMap(result => {
return [
new a.GetTimeSlotsSuccess(
ItemSearchAdaptor.allTimeSlotAdaptor(result)
)];
})
).catch((e: HttpErrorResponse) => {
return Observable.of({});
});
});
誰能建議我可以使用任何方法來延遲 API 發送之間的延遲。
參考解法
方法 1:
getTimeSlots() method should return the observables with delay as shown give below. delay operator can be used to delay the request.
Be aware that if any of the inner observables supplied to forkJoin error you will lose the value of any other observables that would or have already completed if you do not catch the error correctly on the inner observable. If you are only concerned with all inner observables completing successfully you can catch the error on the outside.
getTimeSlots(pl){
let observables = [];
observables.push(http.doDelete(null, {})
.pipe(delay(1000),
catchError(error => of(error))
))
retur observables;
}