localStorage检索/ getItem返回null

时间:2019-09-10 17:46:09

标签: angular typescript local-storage

我已在我的应用程序中添加了一个主题切换器,它允许我通过打开/关闭开关通过界面更改theme / variable.scss文件。

在刷新/导航时,我希望记住用户的偏好。我有setItem到本地存储,并且显示在我的浏览器本地存储中。

接下来,如果有本地存储可用,我想检索该选择,否则保留默认主题设置。

AppComponent.ts

export class AppComponent implements OnInit {
  currentTheme: string;
  constructor( @Inject(DOCUMENT) private document) {
  }


  ngOnInit() {
    if (localStorage.length > 0) {
      this.currentTheme = JSON.parse(localStorage.getItem(localStorage.localTheme));
    } else {
      this.currentTheme = 'Standard contrast';
      this.document.getElementById('theme').className = 'standard-theme';
    }
  }

  handleThemeChange(event) {
    if (this.currentTheme === 'Standard contrast') {
    this.document.getElementById('theme').className = 'high-contrast-theme';
      this.currentTheme = 'High contrast mode';
    } else {
    this.document.getElementById('theme').className = 'standard-theme';
      this.currentTheme = 'Standard contrast';
    }
    localStorage.setItem('localTheme', this.currentTheme);
  }

}

localStorage.localTheme会按预期返回“标准对比度”或“高对比度模式”-我需要使用它来更新currentTheme,以便用户选择保持刷新状态-但是当我调试时,它以{{ 1}}

更新:

null

这行似乎是问题所在,尽管this.currentTheme = JSON.parse(localStorage.getItem(localStorage.localTheme)); 返回值(localStorage.localTheme) = null吗?

一点帮助将不胜感激!谢谢

4 个答案:

答案 0 :(得分:0)

在本地存储中设置localTheme时,您设置的是字符串,而不是序列化的对象。  所以不要解析

尝试:

this.currentTheme = localStorage.getItem(localStorage.localTheme);

答案 1 :(得分:0)

尝试使用getter和setter并使用this.localTheme

进行访问
get localTheme() {
    return JSON.parse(localStorage.getItem('localTheme'));
}

set localTheme(val) {
    localStorage.setItem('localTheme', JSON.stringify(val));
}

答案 2 :(得分:0)

尝试一下

const currentTheme = this.currentTheme;
localStorage.setItem('localTheme', currentTheme);

console.log(typeof this.currentTheme)来查看类型是什么

答案 3 :(得分:0)

@Heretic Monkey在API更新中是正确的。因此,我可以使用它:

  ngOnInit() {

    if (localStorage.length > 0) {
      this.currentTheme = localStorage.getItem("localTheme");
      const themeClass = this.currentTheme === 'Standard contrast' ? 'standard-theme' : 'high-contrast-theme';
      this.document.getElementById('theme').className = themeClass;
    } else {
      this.currentTheme = 'Standard contrast';
      this.document.getElementById('theme').className = 'standard-theme';
    }

  }
相关问题