是否可以在状态B的选择器内使用状态A的数据?

时间:2018-04-17 12:17:07

标签: ngxs

我正在尝试将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。当currentSection驻留在SectionState内时,是否可以将currentSection放在一个驻留在QuestionFlowState内的选择器中?我已经尝试了下面的代码(带有填充的商店)但没有成功。

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

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

编辑: After some back and forth with @Danny Blue我们已经找到了添加父状态的解决方案,该状态将包含选择器所需数据的状态作为子节点(可以在@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;
  }
}

1 个答案:

答案 0 :(得分:1)

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

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