Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

}
like image 712
Soufiane Rabii Avatar asked Dec 05 '25 08:12

Soufiane Rabii


2 Answers

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

like image 85
Prathmesh Dali Avatar answered Dec 07 '25 01:12

Prathmesh Dali


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

like image 22
Leandro Q Avatar answered Dec 07 '25 01:12

Leandro Q