【问题标题】:Using localStorage() in Angular在 Angular 中使用 localStorage()
【发布时间】:2017-11-18 15:58:30
【问题描述】:

我正在尝试使用 localStorage 在我的应用程序中保存语言偏好,但我似乎无法获得它。谁能看到为什么这不起作用以及我该如何解决?

这是我的代码:

export class AppComponent implements OnInit {
  title: string = 'app';
  currentLanguage = localStorage.getItem('language');
  currentPage: string;
  @ViewChild('bottom') bottomSection: ElementRef;
  @ViewChild('top') topSection: ElementRef;


  constructor(private global: GlobalProvider, private translate: TranslateService, private scrollService: ScrollToService, private elementRef: ElementRef, private route: ActivatedRoute, private router: Router) {
    translate.setDefaultLang('en');
    this.changeLanguage('en');
  } 

  changeLanguage(language: string) {
    this.translate.use(language);
    this.currentLanguage = language;
    localStorage.setItem('language',language);
  } 

【问题讨论】:

    标签: javascript angular local-storage angular-local-storage


    【解决方案1】:

    将声明更改为,

     currentLanguage :string;
    

    然后,

    changeLanguage(language: string) {
        this.translate.use(language);
        this.currentLanguage = language;
        localStorage.setItem('language',language);
      } 
    

    【讨论】:

    • 我之前设置过,但仍然无法正常工作
    【解决方案2】:

    localStorage 无法被打字稿识别,因此它会在编译时抛出错误。为localStorage 声明环境变量,以便打字稿分析localStorage 变量已被定义并且工具系统不会对它大喊大叫。

    //write below line `AppComponent` class 
    declare var localStorage: any;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 2019-05-27
      • 1970-01-01
      • 2019-01-05
      • 2017-10-30
      • 2012-06-22
      • 1970-01-01
      相关资源
      最近更新 更多