Soufiane Rabii
Soufiane Rabii

Reputation: 427

Angular 2 - Storing and Getting Objects array from localStorage

I'd like to store an array of objects in localStorage.

This is snippet of my code storing the array of objects at component stage.

this._authenticationService.getProfilByLogin(this.form.value.j_username)
  .subscribe(result => {
     console.log('inside getting profils');
     console.log(result.json().ecomServices);
     localStorage.setItem('services_assigned', result.json().ecomServices);
  }, error => {

This is the code trying to get it back in another component.

import {Component, OnInit} from '@angular/core';
  import {EcomService} from "../../model/EcomService";

  @Component({
    selector: 'app-sidebar-nav',
    templateUrl: './sidebar-nav.component.html',
    styleUrls: ['./sidebar-nav.component.css']
  })
  export class SidebarNavComponent implements OnInit {


    public ecomServices: EcomService[] = [];

    constructor() {
    }

    ngOnInit() {
      this.ecomServices = localStorage.getItem('services_assigned');
    }
  }

This is my model class

export class EcomService {

  public eseCode: number;
  public eseLabel: string;

}

Upvotes: 3

Views: 22789

Answers (3)

iliya.rudberg
iliya.rudberg

Reputation: 789

In my project i have just simply create storage service to work with localStorage:

@Injectable()
export class CacheService {

    constructor() {}

    public get(key) {
        const data = localStorage.getItem(key);
        return !_.isEmpty(data) ? _.cloneDeep(JSON.parse(data)) : [];
    }

    public set(data, key) {
        localStorage.setItem(key, JSON.stringify(data));
    }

    public reset() {
        localStorage.clear();
    }
}

Upvotes: 0

Leandro Q
Leandro Q

Reputation: 221

The problem with the answer from Prathmesh is that if the key 'services_assigned' doesn't exist in localStorage you will get an error.

So the best way to get the array is:

this.ecomServices = JSON.parse(localStorage.getItem('services_assigned') || '[]');

Note how that provides a default (empty array) if getItem returns null because we've never stored our services there.

To store the array:

localStorage.setItem('services_assigned', JSON.stringify(this.ecomServices));

Upvotes: 4

Prathmesh Dali
Prathmesh Dali

Reputation: 2350

While storing in local storage store something like this

localStorage.setItem('services_assigned', JSON.stringify(this.ecomServices));

While getting back do something like this.

this.ecomServices = JSON.parse(localStorage.getItem('services_assigned'));

Upvotes: 16

Related Questions