It seems that every time you save data in Angular, the local storage array gets overwritten

While using Angular, I encountered an issue with saving to local storage. The code works fine for saving items initially, but on refreshing the page and trying to add more objects to the local storage array, it overwrites instead of appending. Can you help me identify where I might be going wrong?

The array public playlist = []; is shared across components through a service, and this is where the objects are being pushed.

component.ts

import { Component, OnInit } from '@angular/core';
import { PlaylistService } from '../../../services/playlist.service';
import { faSave } from '@fortawesome/free-solid-svg-icons';

@Component({
  selector: 'app-playlist-view',
  templateUrl: './playlist-view.component.html',
  styleUrls: ['./playlist-view.component.scss']
})
export class PlaylistViewComponent implements OnInit {

  faSave = faSave;

  constructor(private list: PlaylistService) { }

  ngOnInit() {
        this.list.getPlaylist();

  }
}

Playlist.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class PlaylistService {

  public playlist = [];

  savePlaylist() {
    this.playlist = JSON.parse(localStorage.getItem('playlist'));
    localStorage.setItem('playlist', JSON.stringify(this.playlist));
    console.log('Saved', this.playlist);
  }

  getPlaylist() {
    if (localStorage.getItem('playlist') == null) {
      this.playlist = [];
    } else {
      this.playlist = JSON.parse(localStorage.getItem('playlist'));

    }
  }

  constructor() { 
  }
}

Answer №1

You are observing the process of overriding, which is correct based on the provided code. When saving in localstore, you retrieve the existing data from localstore and then assign it to playlist. Subsequently, you save the updated playlist back into localstore.

The correct approach is to first save the playlist in localstore and then assign it to the class-level playlist.

The modified savePlaylist function should be as follows:

Playlist.service.ts

savePlaylist() {
    // Saving the data first 
    localStorage.setItem('playlist', JSON.stringify(this.playlist));
    // Retrieving the saved data afterwards
    this.playlist = JSON.parse(localStorage.getItem('playlist'));
    console.log('Saved', this.playlist);
}

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

Tips for creating a seamless merge from background color to a pristine white hue

Seeking a seamless transition from the background color to white at the top and bottom of the box, similar to the example screenshot. Current look: The top and bottom of the box are filled with the background color until the edge https://i.stack.imgur.com ...

Retrieve information from an array of objects by utilizing a separate array

There are two separate arrays provided below: ages = [20,40,60]; doctors = [{ "name": "Moruu", "age": 18, "sex": "Male", "region": "Africa" }, { "name": "Khol ...

Angular 2: The *ngFor directive is unable to locate a suitable differing framework

Below is the code for client.service.ts clients: Client[]; getClientList() { let headers = new Headers(); headers.append('Content-Type', 'application/json'); let authToken = localStorage.getItem('auth_token&apo ...

Error: TypeORM entity import token is not recognized

Currently, I am facing a peculiar error while transpiling my TypeScript code to JavaScript using TypeORM. The error message that pops up is as follows: (function (exports, require, module, __filename, __dirname) { import { Entity, PrimaryGeneratedColumn, M ...

Implementing updates to a particular value in a sub-document in Cosmos DB using Azure Function and TypeScript

I am looking to update a specific value called statutProduit in a sub-document residing within a document collection in Azure Cosmos DB. This will be accomplished using an HttpTrigger Azure Function that requires two parameters: the document ID (id) and th ...

Utilizing TypeScript with Express.js req.params: A Comprehensive Guide

Having an issue with my express.js controller where I am unable to use req.params The error message being displayed is 'Property 'id' is missing in type 'ParamsDictionary' but required in type 'IParam'.' I need a w ...

Port 4200 is currently being utilized. Please utilize the '--port' option to designate an alternative port

Hi there, I am currently running an Angular 2 app with Express as the backend and encountering the following issue: [3] Port 4200 is already in use. Use '--port' to specify a different port. [3] [nodemon] app crashed - waiting for file changes b ...

Custom fields provided by Express are not accessible within routes

In my customExpress.d.ts file, I have defined an extended type: declare namespace Express { export interface Request { user: { id: string; }; } } I have also configured it in the tsconfig.json file: ... "typeRoots": ["sr ...

Upon attempting to run ionic for iOS, an error was encountered regarding the arm64 and armv7 architectures

I'm currently in the process of developing a mobile application for both Android and iOS platforms utilizing Ionic version 1. Here is a breakdown of the software versions I'm working with: cordova: 7.0.1 ionic: 2.2.2 ios-deploy: 1.9.2 ios-sim: ...

Is there a way to stop TSC from performing type checking on projects within the node_modules directory

I'm encountering an issue where tsc is performing type-checking on files within the node_modules directory, resulting in errors like: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="513c287c21233e3b34322511617f617f ...

Tips for testing an Angular 6 service with a dependency that utilizes private methods and properties to alter the output of public methods and properties

I've encountered a challenge while attempting to write a Jasmine/Karma test for an Angular 6 app. The test is for a service in my application that relies on another service with private properties and methods, causing my tests to consistently fail. W ...

``There seems to be an issue with Angular2 routing not functioning properly due to the presence of

Seeking assistance with an issue I'm facing. I am attempting to pass parameters in routing. However, when my parameter contains a slash symbol, Angular interprets the text after the slash as another parameter, causing my routing to fail. { path: &ap ...

Tips for linking a checkbox in Angular 7

<form #checkboxForm="ngForm" name="checkboxForm"> <table><th>Unique Grouping</th> <th>Specific Status</th> <tr> <td><label for="checkbox" class="checkbo ...

What is the best way to connect a series of checkboxes within a form utilizing Angular?

I created a form with checkboxes that allow users to select multiple options. However, when I submit the form, instead of receiving an array of objects representing the checked checkboxes, I'm not getting anything at all. Here is what I see in the co ...

The specified JSX element does no possess any constructors or callable signatures

The root element on the right side of my page is a simple React element that I am currently using. Can you help me troubleshoot and fix the error that is being displayed? https://i.sstatic.net/xdDyn.png ...

Ways to transfer selected options from a dropdown menu to a higher-level component

I am currently in the process of configuring a modal component that showcases various data from a specific record to the user. The user is provided with a Bulma dropdown component for each field, enabling them to make changes as needed. To streamline the c ...

Unable to connect to Alpine store from an external source due to a typescript error

Here is how I have configured my Alpine store: Alpine.store( 'state', ({ qr: '' })) Now, I am attempting to update it from an external source as follows: Alpine.store( 'state' ).qr = 'test' However, I am encounte ...

Using a JSON array in PHP script

I'm trying to incorporate a JSON array within my PHP code, specifically within a for loop where I need to split the array into two parts and then merge them back together. Unfortunately, my current approach has not been successful. The purpose of this ...

Limit the parameter of a TypeScript method decorator based on the method's type

Is it possible to generically restrict the argument of a method decorator based on the type of the method it is applied to? I attempted to obtain the method's type that the decorator is applied to using TypedPropertyDescriptor<Method>. However, ...

The functionality of the disabled button is malfunctioning in the Angular 6 framework

Just starting out with angular 6 and I'm using formControl instead of FormGroup for business reasons. app.component.html <button class="col-sm-12" [disabled]="comittee_Member_Name.invalid && comittee_Member_Number.invalid && c ...