Angular 2 - Storing and Getting Objects array from localStorage

Viewed 19352

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;

}
3 Answers

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

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