在Angular中使用localStorage()

时间:2017-11-13 02:21:12

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

我正在尝试使用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);
  } 

2 个答案:

答案 0 :(得分:0)

将声明更改为,

 currentLanguage :string;

然后,

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

答案 1 :(得分:0)

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

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