Ways to store data in the localStorage directly from a server

I'm facing an issue - how can I store data in localStorage that was received from the server? Should I use localStorage.setItem for this purpose? And how do I handle storing an array in localStorage? Or am I missing something here?

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


}

Answer №1

When using Local Storage, it is important to remember that it stores key/value pairs as strings. Therefore, you must serialize the data before saving it and deserialize it when retrieving it.

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

const info = JSON.parse(localStorage.getItem('mykey'));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Automated login feature in JQuery utilizing localStorage

I've been working on implementing an automatic login feature for users using the "Remember Me" functionality. Below is the code I have written, but unfortunately, it's not logging in users automatically: if (localStorage.getItem("username") != ...

Identifying the moment when the body scroll reaches the top or bottom of an element

I have been experimenting with javascript and jquery to determine when the window scroll reaches the top of a specific element. Although I have been trying different methods, I have yet to see any successful outcomes: fiddle: https://jsfiddle.net/jzhang17 ...

An error occurred while trying to upload the image: Undefined property 'subscribe' cannot be read

Recently, I implemented a create post function that allows users to fill in the title, content, and upload an image. However, I encountered an issue where the progress bar fills up and the image gets uploaded to Firebase successfully, but it doesn't a ...

Omit a specific page from the primary Next.js layout within the application directory

In my project, I have a main layout file located at /app/layout.tsx and separate authentication pages. I want the authentication pages to have their own custom layout defined in the file /app/auth/layout.tsx. The issue I am facing is that the main layout ...

Conceal the Angular Bootstrap modal instead of shutting it down

I am utilizing Angular Bootstrap Modal to launch multiple modals, including a video player. http://angular-ui.github.io/bootstrap/#/modal My goal is to maintain the video's current position even when the modal is closed. This way, when I reopen the ...

Updating the Scale of the Cursor Circle on my Portfolio Site

I attempted to find tutorials on creating a unique circle cursor that can hide the regular mouse cursor as well. After implementing it with a difference blend mode, I encountered an issue where I wanted the scale to change when hovering over a link. The ...

Encountering a build error in ng serve right after running npm install

After deleting the node_modules directory and rebuilding it with npm install, I encountered an error in my angular2 app when using cmd ng serve. Error: 'common-tags' module not found at Function.Module._resolveFilename (module.js:337:15) ...

Node.js UDP broadcast to subnet not working properly in Linux

Here is a simplified Node JavaScript code snippet for testing purposes. Click here to view the code on GitHub This code creates a socket for each interface address, calculates the subnet broadcast address, and then sends data every second for 4 seconds t ...

Improving Three.js performance for a single, substantial model

I am currently developing a hybrid file browser and 3D model viewer. My goal is to seamlessly load models of various formats, specifically .OBJ files, into the scene while maintaining a smooth framerate with the help of orbitControls.js. Most of the optim ...

jQuery Animated List - Nested items are unresponsive to clicks

Looking to create a dynamic nested list using jQuery for animations, but unsure of the best approach. Currently, I'm adjusting the length of the parent list item and revealing the nested items. The issue is that the parent item's length covers ...

Creating a Form Input Field Based on a Selection List

I'm in the process of developing a small app to boost my productivity at work. Currently, I have some html/js code that includes a ul with a search filter. When I select an option, it opens a new tab with relevant text. Ideally, I want the outcome to ...

Is it possible to deceive Array.isArray?

Although I have a good understanding of prototypes, I encountered some confusion when I attempted the following: var obj = {}; Object.setPrototypeOf(obj, Array.prototype); console.log(Array.isArray(obj)); // false? What's even more perplexing: var ar ...

serve angular6 application using fastify

I have a question regarding my setup. I am working on an Angular 6 application with a Fastify back-end. Fastify serves the application like this: fastify.use(['/'], serveStatic(path.join(__dirname + '/../dist/'))); The Angular build i ...

Navigating the intricacies of sub-State mapping in Nuxtjs

I have set up a state called ~/store/modules/general/index.js Within this state, there are Actions named get_info and get_pages, as well as states named info and pages. When I use ...mapActions({ getInfo: 'modules/general/get_info' getPages: ...

Error TS2304: Unable to locate identifier 'QRScanner'

I am currently exploring https://www.npmjs.com/package/cordova-plugin-qrscanner in order to implement a QR scanning feature in my mobile application. As part of the initial steps, I have written the following code snippet in my typescript file: function o ...

What is the best way to iterate through an ID using jQuery?

After pulling the list of doctors in my area from the database and displaying it on my webpage, I now want to load each doctor's "About" content inside a Bootstrap modal. I added an "about" column within the same database table where the doctors' ...

Adjust the opacity of a div's background without impacting the children elements

I am currently working on a dynamic content display in my HTML page using some knockout code. The setup looks like this: <section id="picturesSection" class="background-image" data-bind="foreach: { data: people, as: 'person'}"> <div ...

The Heroku Node.js application encountered an issue when trying to apply the style due to an incompatible MIME

As a complete beginner in Node.js and Express, I am encountering some errors from the console. When trying to load my CSS file from '', I receive the following error: "Refused to apply style because its MIME type ('text/html') i ...

Miscalculation occurred when attempting to add or subtract values from various inputs

My goal is to calculate the sum and rest of two different values after adding or subtracting. For instance, I have a Total variable = 500, along with two input fields - one for MXN and the other for USD. Additionally, there is a USD variable set at 17.5. T ...

Error message TS2339: The method 'findAll' is not defined in the current context

Despite following the Sequelize guide for TypeScript configuration, I am unable to resolve an issue with my database connection. The connection is active, but I am struggling with a specific type problem: TSError: ⨯ Unable to compile TypeScript: controll ...