【发布时间】:2021-05-19 09:32:23
【问题描述】:
我有一个 DOM 块:
<div (click)="toggle(block)">
<div *ngIf="block.opened">
<div *ngFor="let item of block.items"></div>
</div>
</div>
通过单击我调度操作以从服务器加载数据并在块中显示此数据:
toggle(block: RegistryGroup) {
this.store.dispatch(RegistryActions.ToggleRegistryBlockAction(block));
this.store.dispatch(RegistryActions.LoadRegistryLayersAction(this.block));
}
第一个事件ToggleRegistryBlockAction 将block 的属性更改为真/假。
第二个LoadRegistryLayersAction通过block.id向服务器发出请求,并将数据返回到与block相同的状态到属性block.items = Server Response;
在我收听动作的效果方面LoadRegistryLayersAction:
loadRegistriesLayers$: Observable<Action> = createEffect(() =>
this.actions$.pipe(
ofType(RegistryActions.LoadRegistryLayersAction),
filter(
(registryGroup) =>
registryGroup.items && !registryGroup.items.length
),
switchMap((registryGroup: RegistryGroup) =>
from(this.registry.getRegistryLayers(registryGroup.Id)).pipe(
map((layers: { [key: string]: RegistryLayerItemGeneric[] }) => {
return RegistryActions.SuccessLoadRegistryLayersAction({
payload: {
layers: this.registry.createLayersMapWithObjects(layers),
registryGroupId: registryGroup.Id,
},
});
}),
catchError((error: Error) => {
return of(RegistryActions.ErrorRegistryLayersAction(error));
})
)
)
)
);
我filter 操作并检查数据是否已经存在。为此,我检查块是否有 registryGroup.items && !registryGroup.items.length。
问题是有时在执行后这个效果服务器会返回空的[]。所以下一次,当用户请求它时,它会重复发送请求。
如果加载了数据,如何修复它并且不触摸服务器?
【问题讨论】:
-
作为解决方案,我可以将额外的标志属性添加到块对象为
loaded: boolean。但我不想污染物体
标签: angular redux ngrx ngrx-store ngrx-effects