3

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;

}
2
  • What is the problem ? Commented Jul 20, 2017 at 10:51
  • my code can't hold and array of objects in localStorage and gets it back from another component. Commented Jul 20, 2017 at 10:54

3 Answers 3

16

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

Sign up to request clarification or add additional context in comments.

Comments

4

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

1 Comment

If storage doesn't have the value, it will throw error. Good that we have provided an empty array if getItem returns null. Thanks...
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.