【问题标题】:How prevent loading data second time in NgRx?如何防止在 NgRx 中第二次加载数据?
【发布时间】: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));
  }

第一个事件ToggleRegistryBlockActionblock 的属性更改为真/假。 第二个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 &amp;&amp; !registryGroup.items.length

问题是有时在执行后这个效果服务器会返回空的[]。所以下一次,当用户请求它时,它会重复发送请求。

如果加载了数据,如何修复它并且不触摸服务器?

【问题讨论】:

  • 作为解决方案,我可以将额外的标志属性添加到块对象为loaded: boolean。但我不想污染物体

标签: angular redux ngrx ngrx-store ngrx-effects


【解决方案1】:

有多种解决方案:

  • 保留一个状态属性,它可以是loadingloadedempty、...
  • 保留在状态中获取的 id 列表,并在发送请求之前检查此列表
  • 不检查registryGroup.items.length,将数组初始化为null

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多