我尝试使用效果多次触发后端调用,调用已启动但正在取消。不确定是效果问题还是HTTP错误。我的效果是正确触发调用,但它们只是没有最终确定。
我正在使用第三方 API。我正在进行的调用使用 OData,并且每次调用的响应限制为 500 个项目。我需要的记录总数是 6440 条,这意味着我必须调用后端 13 次才能获取所有数据。之前 API 没有提供获取查询总数的调用,但他们对此进行了修改,以便我可以升级我的算法。
如果没有计数,我执行了以下步骤,这些步骤有效,但速度很慢,因为它是同步运行的:
现在我已将代码更改为在获取结果集计数后异步工作。我在获取计数后调度操作数组,这是我为此使用的编码:
loadCollectionCount$ = createEffect(() =>
this.actions$.pipe(
ofType(this.loadActionGroup.loadItemCollection),
withLatestFrom(this.store.select(this.loadedStatus)),
switchMap(([{ }, loaded]) => {
if (!loaded) {
return this.loadService.getListCount(this.filterValue).pipe(
switchMap((result: number) =>{
let act: Action[] = [ this.loadActionGroup.loadItemCollectionCountSuccess({ count: result }) ];
for (let i = 0; i < result; i = i + 500) {
act.push(this.loadActionGroup.loadItemCollectionWithSkip({skip:i}));
}
return act;
} ),
catchError(error => {
console.log(error, `${this.typeName} effects - loadCollection`);
return of(this.loadActionGroup.loadItemFailure({ error: { ...error } }))
})
)
} else {
return of();
}
})
)
);
loadItemCollectionWithSkip$ = createEffect(() =>
this.actions$.pipe(
ofType(this.loadActionGroup.loadItemCollectionWithSkip),
switchMap((action) => {
return this.loadService.getListOdata(this.filterValue, action.skip).pipe(
map((items: T[]) =>{
return this.loadActionGroup.loadItemSuccess({ items })
})
)
})
)
);
但是,这会导致前 12 个调用被取消,并且只有最后一个调用完成,正如您在网络页面结果中看到的那样。因此,操作被触发并且调用被正确地进行,它们只是没有被最终确定。
问题就在这里
switchMap((action) => {
return this.loadService.getListOdata(this.filterValue, action.skip)
当新事件到来时,switchMap 运算符取消先前的事件“处理”。这就是为什么您在网络选项卡中取消了 http 请求。简单的解决方法是将其替换为
concatMap
。这样他们就会按顺序一一被解雇。这里的坏处是他们不会并行获取数据。