【问题标题】:NGXS - set property within objectNGXS - 在对象内设置属性
【发布时间】:2020-07-03 07:22:46
【问题描述】:

我正在尝试将我的站点配置作为 NGXS 中的一个对象。而不是创建一个动作来为对象的每个属性设置值 - 我希望允许一个动作包含属性名称和新值。然后我会更新该属性。我尝试了几种方法,但似乎都没有奏效....

import { State, Action, Selector, StateContext } from '@ngxs/store';
import { SetLayout, SetTheme, SetLayoutConfigurationProperty } from './layout.actions';
import { Injectable } from '@angular/core';
import { LayoutConfiguration } from './layout.types';

export interface LayoutStateModel {
  currentTheme: string;
  configuration: LayoutConfiguration;
}

@State<LayoutStateModel>({
  name: 'layout',
  defaults: {
    currentTheme: 'light',
    configuration: {
      ShowAvatar: true,
      ShowMessages: true,
      ShowSearch: true,
      ShowShortcuts: true,
      ShowSidebarAlerts: true,
      ShowSidebarUserMenu: true,
    },
  },
})
@Injectable()
export class LayoutStateModule {
  @Selector()
  public static getCurrentTheme(state: LayoutStateModel): string {
    return state.currentTheme;
  }
  @Selector()
  public static GetConfiguration(state: LayoutStateModel): LayoutConfiguration {
    return state.configuration;
  }

  @Action(SetTheme)
  public SetTheme({ patchState }: StateContext<LayoutStateModel>, { payload }: SetTheme): void {
    patchState({ currentTheme: payload });
  }
  @Action(SetLayoutConfigurationProperty)
  public SetLayoutConfigurationProperty(
    { getState, patchState }: StateContext<LayoutStateModel>,
    { payload }: SetLayoutConfigurationProperty
  ): void {
    patchState({ configuration: { ...getState().configuration, [payload.property]: payload.value } });
  }
}

动作是(我确定你不需要这个代码)

export class SetLayoutConfigurationProperty {
  public static readonly type = '[Layout] Set confiuration property change';
  constructor(public payload: { property: string; value: boolean }) {}
}

但是触发动作 SetLayoutConfigurationProperty 似乎会导致无限循环。任何帮助将不胜感激

【问题讨论】:

  • 这对我来说看起来不错,它是 SetLayoutConfigurationProperty 动作的无限循环被调度吗?你有什么订阅了这部分状态并在它改变时调度一个动作吗?
  • 谢谢 Michael - 我订阅了显示 LayoutConfiguration 选项的表单 - 在初始绑定期间表单值似乎发生了变化。请添加回复,以便我可以相信这个答案:)

标签: angular ngxs


【解决方案1】:

这对我来说看起来不错,它是 SetLayoutConfigurationProperty 动作的无限循环被调度吗?

你有什么订阅了这部分状态并在它改变时调度一个动作?

这似乎很可能会导致此类问题。为了调试,我会在动作构造函数中设置一个断点,以查看它被调度的位置以及原因

【讨论】:

    猜你喜欢
    • 2015-02-12
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多