[Fixed] How to add data in localStorage from server


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 {
    public name:string,
    public username:string,
    public email:string,
    public phone:string,
    public website:string
  ) {}

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

    private httpClient: HttpClient,
  ) { }

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



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