[Fixed] How to add data in localStorage from server

Issue

I have some problem. How can I save data in localStorage that had been responsed from server? Maybe I should use localStorage.setItem? But how to put an array here? Or I made a mistake?

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
export class Contact {
  constructor(
    public name:string,
    public username:string,
    public email:string,
    public phone:string,
    public website:string
  ) {}
}

@Component({
  selector: 'app-contact-list',
  templateUrl: './contact-list.component.html',
  styleUrls: ['./contact-list.component.css']
})
export class ContactListComponent implements OnInit {
  
  contacts: Contact[] = [];

  constructor(
    private httpClient: HttpClient,
  ) { }

  ngOnInit(): void {
    this.contacts = [];
    this.getContacts();
  }
  getContacts() {
    this.httpClient.get<any>('some url').subscribe(
      response => {
        console.log(response);
        this.contacts = response;  
      }
    );
  }


}

Solution

Local Storage stores pairs of key/value, which are strings. So you have to serialize it when you save, and deserialize when you try to retrieve this data.

const data = ['value 1', 'value 2' ... ];
localStorage.setItem('somekey', JSON.stringify(data));

const data = JSON.parse(localStorage.getItem('somekey'));

Leave a Reply

(*) Required, Your email will not be published