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

Receiving an array with a specific key using ngrx/selector and ngrx/entities

如何使用选择器只获取特定键的数据?

也就是说,我有 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}));
  }

在您的选择器中,如果您想获得与您的目录代码匹配的对象,请使用过滤器。

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));