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

Is it possible to use data from state A inside a selector in state B?

我正在试用 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 中创建一个选择器,returns 每个属于 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;
  }
}

如果问题有什么missing/unclear,请告诉我。

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

您可以在父状态 class 添加选择器,这样它就可以访问两个子状态。

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