Victor Mendes
Victor Mendes

Reputation: 179

Angular 2 LocalStorage key

I'm working with LocalStorage. In constructor I had done it:

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

But doing it I'll store the data in array and I think it isn't good.

So, I did it:

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)
}
}

But I got an error, TypeError: Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefined.

To save data I do it:

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]));
    }
}

How could I get the multiples datas from localStorage? Does anyone know how I fix this problem?

Upvotes: 0

Views: 1534

Answers (3)

Joshua J Wilborn
Joshua J Wilborn

Reputation: 526

Use to $localStorage service

https://github.com/gsklee/ngStorage

It easily allows you to interact with the localStorage object and calls digests when data changes.

You can easily add/remove variables like so

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

Upvotes: 0

Bruno João
Bruno João

Reputation: 5535

I made a service do handle the localStorage. Maybe this can help you:

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);
  }

}

Upvotes: 0

Aravind
Aravind

Reputation: 41573

You should be using the localstorage injected into constructor

Probably you might have forgot this key word as below

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

Alternatively, you can use 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

Upvotes: 1

Related Questions