使用ngrx / selector和ngrx / entities接收具有特定键的数组

问题描述 投票:0回答:1

如何使用选择器仅使用某个键获取数据?

也就是说,我有4个菜单,每个菜单都有一个特定的catalogCode,用户在点击时从服务器获取特定菜单的列表。此列表中的每个元素都有一个id = code + catalogCode。也就是说,此菜单中所有元素的catalogCode将是相同的。那么如何从商店获得特定catalogCode的物品清单?

我正在尝试这样做:selectByCatalogCode

export const selectCatalogItemState: MemoizedSelector<object, State> = createFeatureSelector('CatalogItem');
export const selectCatalogItemAll: MemoizedSelector<object, CatalogItem[]> = createSelector(selectCatalogItemState, selectAll);
export const selectByCatalogCode = () => createSelector(selectCatalogItemAll, (entities: CatalogItem[], props: { catalogCode: string }) => entities[props.catalogCode]);

但是,当在组件中使用时,这不起作用,始终显示未定义的值

  getCatalogItems(catalogCode: string) {
    this.catalogItemStore.dispatch(new CatalogItemStoreAction.LoadByCatalog({catalogCode: catalogCode}));
    this.catalogItemStore.select(CatalogItemStoreSelector.selectByCatalogCode(), {catalogCode: catalogCode}).subscribe(
      a => console.log(a)
    );
  }

目录-item.ts

export class CatalogItem {
  constructor(public code: string,
              public catalogCode: string,
              public title: string,
              public data: object) {
  }
}

我只提供了部分代码。如有必要,我可以提供整个商店的代码。

effect.ts

  @Effect()
  getCatalogEffect$: Observable<Action> = this.action$
    .pipe(
      ofType<featureAction.GetByCatalog>(featureAction.ActionTypes.GET_BY_CATALOG),
      switchMap(action => this.store.select(CatalogItemStoreSelector.selectByCatalogCode(action.payload.catalogCode))
        .pipe(
          take(1),
          filter(catalogItems => !catalogItems),
          map(() => new featureAction.LoadByCatalog({catalogCode: action.payload.catalogCode})),
        )
      )
    );
  @Effect()
  loadByCatalog$: Observable<Action> = this.action$
    .pipe(
      ofType<featureAction.LoadByCatalog>(featureAction.ActionTypes.LOAD_BY_CATALOG),
      switchMap(action => this.catalogItemService.listByCatalog(action.payload.catalogCode)
        .pipe(
          map(catalogItems => new featureAction.LoadByCatalogSuccess({catalogItems: catalogItems})),
          catchError(error => of(new featureAction.LoadByCatalogError({error: error}))),
        )
      )
    );

目录-list.component.ts

  getCatalogItems(catalogCode: string) {
    this.catalogItemStore.dispatch(new CatalogItemStoreAction.GetByCatalog({catalogCode: catalogCode}));
  }
angular ngrx ngrx-store ngrx-entity
1个回答
0
投票

在选择器中,如果要获取与catalogCode匹配的对象,请使用过滤器。

TS:

this.catalogItemStore.select(CatalogItemStoreSelector.selectByCatalogCode(catalogCode)).subscribe(
      a => console.log(a)
    );

选择:

export const selectByCatalogCode = (catalogCode: string) => createSelector(selectCatalogItemAll, (entities: CatalogItem[]) => entities.filter((item: CatalogItem) => item.catalogCode === catalogCode));
© www.soinside.com 2019 - 2024. All rights reserved.