开发者问题收集

Angular 2 LocalStorage 键

2017-03-24
1507

我正在使用 LocalStorage。在构造函数中我这样做了:

this.currentData = (localStorage.getItem('currentData')!==null) ? JSON.parse(localStorage.getItem('currentData')) : [ ];

但这样做我会将数据存储在数组中,我认为这不好。

所以,我这样做了:

constructor(){
if(this.currentData !== null  && this.currentData !== undefined) {
    for (var i = this.currentData.length - 1; i >= 0; i--) {
        this.currentData = JSON.parse(localStorage.getItem('currentData-' + i));
        console.log('currentData if:' + this.currentData)
    }
} else {
    console.log('currentData else:' + this.currentData)
}
}

但我收到错误, TypeError:无法读取未定义的属性“长度” TypeError:无法读取未定义的属性“长度”

为了保存数据,我这样做了:

saveLocalStorage(todo){
    this.objects.push(todo);
    for (var i = this.objects.length - 1; i >= 0; i--) {
        localStorage.setItem('currentData-' + i, JSON.stringify(this.objects[i]));
    }
}

我如何从 localStorage 获取多个数据? 有人知道我如何解决这个问题吗?

3个回答

您应该使用注入构造函数的 localstorage

可能您可能忘记了下面的 this 关键字

this.currentData = (this.localStorage.getItem('currentData')!==null) ? JSON.parse(localStorage.getItem('currentData')) : [  ];

或者,您可以使用 as,

user:any[]={name:'abc',id:1};
  valuFromLocalStorage:any{};
  constructor(private localStorageService: LocalStorageService) {
    this.name = 'Angular2';
    this.localStorageService.add('a',this.user);
    console.log(this.localStorageService.get('a')); 
    this.valuFromLocalStorage= this.localStorageService.get('a')
  }

LIVE DEMO

Aravind
2017-03-24

我创建了一个服务来处理 localStorage。也许这可以帮到你:

import { Injectable } from '@angular/core';

@Injectable()
export class NpStorageService {

  constructor(){
    this.checkIflocalStorageIsAvailable();
  }

  private checkIflocalStorageIsAvailable = () => {
    let type = '';
    try {
      let testKey = '__np_storage_test__' + Date.now();
      type = 'localStorage';
      localStorage.setItem(testKey, 'work');
      localStorage.removeItem(testKey);
      type = 'sessionStorage';
      sessionStorage.setItem(testKey, 'work');
      sessionStorage.removeItem(testKey);
      return true;
    }
    catch(e) {
      console.error('NpStorageService => Cannot find ' + type + ' on this browser.');
      return false;
    }
  }

  get = (key?: string) => {
    return JSON.parse(localStorage.getItem(key));
  }

  set = (key: string, value: any): boolean => {
    try {
      localStorage.setItem(key, JSON.stringify(value));
      return true;
    }
    catch(e) {
      return false;
    }
  }

  remove = (key: string) => {
    return localStorage.removeItem(key);
  }

}
Bruno João
2017-03-24

使用 $localStorage 服务

https://github.com/gsklee/ngStorage

它允许您轻松地与 localStorage 对象进行交互,并在数据发生变化时调用摘要。

您可以轻松添加/删除变量,如下所示

$localStorage.myObject = {array: [1,2,3,4]};
Joshua J Wilborn
2017-03-27