Angular 2 LocalStorage键

时间:2017-03-24 20:03:43

标签: javascript html5 angular local-storage

我正在使用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: Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefined

要保存数据,请执行以下操作:

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 个答案:

答案 0 :(得分:1)

您应该使用注入构造函数的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

答案 1 :(得分:0)

我做了一个服务来处理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);
  }

}

答案 2 :(得分:0)

使用$ localStorage服务

https://github.com/gsklee/ngStorage

它可以让您轻松地与localStorage对象进行交互,并在数据更改时调用摘要。

您可以轻松添加/删除变量

$localStorage.myObject = {array: [1,2,3,4]};