【发布时间】: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 选项的表单 - 在初始绑定期间表单值似乎发生了变化。请添加回复,以便我可以相信这个答案:)