4

我正在尝试将 Ngxs 作为状态管理系统,并遇到了一个我似乎无法弄清楚的特定用例。在这个用例中,我使用了两个标准化对象(为了便于阅读,我删除了一些不必要的字段)。

export interface Section {
  id: number;
  sequence: number;
  name: string;
  subName: string;
  totalQuestions: number;
  completedQuestions: number;
  selected: boolean;
  questionFlows: QuestionFlow[];
}

export interface QuestionFlow {
  id: number;
  contractId: number;
  parentId: number;
  subSectionId: number;
  path: string;
  question: string;
  type: string;
  answer: string;
  completed: boolean;
  sequenceNumber: number;
  selected: boolean;
  questionFlows: QuestionFlow[];
}

这两个对象驻留在不同的商店中。一个 SectionStore 和一个 QuestionFlowStore。状态模型如下:

export class SectionsStateModel {
  sections: { [id: number]: Section };
  currentSection: Section;
}

export class QuestionFlowsStateModel {
  questionFlows: { [id: number]: QuestionFlow };
  currentQuestionFlow: QuestionFlow;
}

现在我想在 QuestionFlowsState 中创建一个选择器,它返回属于 currentSection 的每个 questionFlow。是否可以在位于 QuestionFlowState 内的选择器内获取 currentSection,而 currentSection 位于 SectionState 内?我已经尝试了下面的代码(有一个填充的商店)但没有成功。

import { SectionsStateModel } from './sections.state';

@State<QuestionFlowsStateModel>({
  name: 'questionFlows',
  defaults: {
    questionFlows: {},
    currentQuestionFlow: null
  }
})
export class QuestionFlowsState {
  @Selector()
  static getQuestionFlowsArrayFromCurrentSection(
    state: QuestionFlowsStateModel,
    sectionState: SectionsStateModel
  ) {
    const questionFlowsFromCurrentSection: QuestionFlow[] = [];

    sectionState.currentSection.questionFlows.forEach(questionFlow => {
      questionFlowsFromCurrentSection.push(state.questionFlows[+questionFlow]);
    });

    return questionFlowsFromCurrentSection;
  }
}

如果问题中有任何遗漏/不清楚的地方,请告诉我。

编辑: 在与@Danny Blue 反复讨论之后,我们找到了添加父状态的解决方案,该状态将包含选择器所需数据的状态作为子状态(可以在@State 装饰器中设置)。要访问这些儿童商店的数据,您需要致电 state.. 并且一切顺利。下面是解决我的问题的最终代码。

import { State, Selector } from '@ngxs/store';

import { SectionsState } from './sections.state';
import { QuestionFlowsState } from './question-flows.state';
import { QuestionFlow } from '../../contract-details.model';
import { SectionsStateModel } from './sections.state';
import { QuestionFlowsStateModel } from './question-flows.state';

@State({
  name: 'parent',
  children: [SectionsState, QuestionFlowsState]
})
export class ParentState {
  @Selector()
  static getParentFlowsArrayFromCurrentSection(
    state
  ) {
    const questionFlowsFromCurrentSection: QuestionFlow[] = [];

    state.sections.currentSection.questionFlows.forEach(questionFlow => {
      questionFlowsFromCurrentSection.push(
        state.questionFlows.questionFlows[+questionFlow]
      );
    });

    return questionFlowsFromCurrentSection;
  }
}
4

1 回答 1

2

您可以在父状态类中添加选择器,使其可以访问两个子状态。

https://ngxs.gitbook.io/ngxs/advanced/sub-states

于 2018-04-17T12:23:08.950 回答