如何使用NGRX保存到本地存储?

发布于 2025-01-25 01:58:11 字数 242 浏览 2 评论 0原文

我正在尝试保存一个简单的菜单状态,无论是“打开”还是“关闭”到浏览器localstorage。我知道我可以使用localstorage.setitem来做到这一点。但是,我的项目正在使用NGRX。有没有更好的方法可以使用NGRX处理此问题?默认情况下,菜单是打开的。如果我关闭它并关闭浏览器并返回,则应将其关闭。

有没有办法使用NGRX或LocalStorage进行更好的解决方案?我只是在学习NGRX。任何帮助都将受到赞赏。

I am trying to save a simple menu state whether it is 'open' or 'close' to the browser localStorage. I know I can do it by using localStorage.setItem. But, my project is using NGRX. Is there a better way to deal this using NGRX? By default, the menu is open. If I close it and close the browser and return back, it should be closed.

Is there a way to do it using NGRX or localStorage is the better solution? I am just learning NGRX. Any help is appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

悟红尘 2025-02-01 01:58:11

您可以在初始状态下设置一个函数,该函数可以从本地存储中获取数据,

StoreModule.forRoot(
    { someReducer: reducer },
    { initialState: getInitialAppState }
  ),

然后在功能中可以执行类似的操作,

export function getInitialAppState() {
    const previousSettings  = localStorage.getItem("settings")
    if (previousSettings  != null) {
         return JSON.parse(previousSettings);
    }
    return {};
}

因此,如果您在以前的设置中的某个点存储了某些设置,则将设置为无效状态。要存储这些设置,您可以在app.component中有一个选择器,也可以在设置中更拟合的列表,只是json。

You can make a function that you set in your initial state that could pull data from local storage

StoreModule.forRoot(
    { someReducer: reducer },
    { initialState: getInitialAppState }
  ),

then in the function you could do something like this

export function getInitialAppState() {
    const previousSettings  = localStorage.getItem("settings")
    if (previousSettings  != null) {
         return JSON.parse(previousSettings);
    }
    return {};
}

So if you stored some settings at one point in a previous setting it will set that as an inistal state. to store these settings you can have a selector in your app.component or somewhere more fitting listing to settings and just JSON.stringify that state you want to store.

秋凉 2025-02-01 01:58:11

不知道什么是最好的。
但是对我而言,NGRX是一件大事,它可能需要太多的设置/初始化代码。
当我执行简单的任务或功能时,我不使用NGRX,我认为许多任务和要求可以通过LocalStorage,Service,可观察到。
但是,如果您想学习NGRX,可以

Not sure what is the best.
But for me NGRX is kind of big thing and it might need so many setting/initializing code.
When I'm doing simple task or feature I don't use NGRX, I think many tasks and requirements can be handled by localStorage, Service, Observable.
However, it's ok if you want to learn NGRX

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文