【问题标题】:Multiples features inside a feature一个特征内的多个特征
【发布时间】:2022-04-26 18:35:01
【问题描述】:

我用AngularNgRx 13 定义了一个Store。我有一个SharedModule,我在其中定义了选择器等组件。每个选择器内容都加载在store 中,这样我就可以避免重复API 调用。

这是这样定义的:

shared.module.ts

/**...*/
 StoreModule.forFeature(clientsFeature),
 StoreModule.forFeature(prioritiesFeature),
/**...*/

客户端.feature.ts

import { createFeature, createSelector, createReducer, on } from '@ngrx/store';
import { ClientDTO } from '@shared/model/client.models';

import * as ClientsActions from './clients.actions';

export const initialState: ClientDTO[] = [];

export const clientsFeature = createFeature({
  name: 'clients',
  reducer: createReducer(
    initialState,
    on(ClientsActions.getClientListSuccess, (state, { clients }): ClientDTO[] => clients)
  ),
});

export const selectClientList = createSelector(clientsFeature.selectClientsState, clients => clients);

优先级功能类似。

我要做的是避免声明每个功能并使用包含所有子功能的“共享”功能。为此,我创建:

索引.ts

import { ActionReducerMap } from '@ngrx/store';
import { ClientDTO } from '@shared/model/client.models';
import { Priority } from '@shared/model/priorities.models';
import { clientsFeature } from './clients/clients.reducer';
import { prioritiesFeature } from './priorities/priorities.reducer';

export const sharedFeatureKey = 'shared';

export interface SharedState {
  clients: ClientDTO[] | null;
  priorities: Priority[] | null;
}

export const reducers: ActionReducerMap<SharedState> = {
  clients: clientsFeature.reducer,
  priorities: prioritiesFeature.reducer,
};

和我的共享模块

    StoreModule.forFeature(fromShared.sharedFeatureKey, fromShared.reducers),

一切都好。

问题

这样做我无法访问列表的内容。我确定我错过了一些东西,但我不知道是什么。我收到这个警告:

ngrx-store.mjs:724 @ngrx/store:状态中不存在功能名称“clients”,因此 createFeatureSelector 无法访问它。确保使用 StoreModule.forRoot('clients', ...) 或 StoreModule.forFeature('clients', ...) 将其导入加载的模块中。如果默认状态是未定义的,就像路由器状态一样,则可以忽略此仅用于开发的警告消息。

另一个与优先级类似。我很确定问题出在选择器上,但是尝试了几个小时后,我找不到解决方案。

未定义的是选择器内容的日志:

    this.store
      .select(selectPrioritiesList)
      .pipe(take(1))
      .subscribe(priorities => {
        console.log('priorities -->', priorities);
      });

我做错了什么?提前致谢

【问题讨论】:

    标签: angular typescript ngrx ngrx-store


    【解决方案1】:

    问题出在选择器上。 因为您添加了一个额外的“共享”层,所以需要更新选择器。

    目前,createFeature 是不可配置的,它使用顶级状态来选择子状态。这意味着您不能使用createFeature 提供的选择器,但您必须手动编写选择器。

    【讨论】:

      猜你喜欢
      • 2017-09-12
      • 2015-08-16
      • 2019-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多