【问题标题】:Try to safe an object to the localStorage with ngxs尝试使用 ngxs 将对象保护到 localStorage
【发布时间】:2020-04-09 23:29:14
【问题描述】:

我正在尝试使用 'ngxs/storage-plugin' 插件版本 3.5.1 将状态对象保存在浏览器的 localStorage 中。使用 ngxs 的原因是我们将 ngxs 用于所有其他状态,并结合 http-client 将状态保存在后端。

我在网上搜索了一个例子,因为 ngxs 的 doc 目前确实很差,但结果也很差。

这是我已经编写的代码。状态运行良好,但在我开始添加本地存储插件后,我迷路了。

settings.actions.ts

export class SetShowHelp {
  static readonly type = '[MySettings] Set my configuration for the flag showHelp';
  constructor(public showHelp: boolean) {}
}

settings.state.ts

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

import {
  SetShowHelp
} from '../actions/mysettings.actions';


export class SettingsStateModel {
  public showHelp: boolean;
  public hideToolbar: boolean
}

@State<SettingsStateModel>({
  name: 'my-settings',
  defaults: {
    showHelp: true,
    hideToolbar: false
  }
})

export class SettingsState {

  @Selector()
  static getShowHelp(state: SettingsStateModel) {
    return state.showHelp;
  }

  constructor() { }


  @Action(SetShowHelp)
  setShowHelp({ patchState }: StateContext<SettingsStateModel>, {showHelp}: SetShowHelp) {
    // patch the state and write into local storage
    patchState({
      showHelp: showHilfe
    });
  }

  .....

}

app.module.ts

  NgxsModule.forRoot(),
  NgxsStoragePluginModule.forRoot({
      key: SettingsState
    }),

如何将“SettingsStateModel”对象写入localStorage?

【问题讨论】:

    标签: angular typescript local-storage ngxs


    【解决方案1】:

    问题是我所在州的名称包含一个不允许的减号。我将名称更改为“mysettings”。我还将app.module.ts 更改为:

      NgxsModule.forRoot([SettingsState]),
      NgxsStoragePluginModule.forRoot({
        key: 'mysettings'
      }),
    

    所有更改后一切正常。

    【讨论】:

      猜你喜欢
      • 2020-09-01
      • 2019-12-31
      • 2023-03-06
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      • 2020-02-26
      • 1970-01-01
      相关资源
      最近更新 更多