Sole
Sole

Reputation: 3340

Local storage array is always over written when saving in Angular

I am using Angular, I am trying to save to local storage, the below code does this fine. But when I refresh the page and try to add more items (objects) to the local storage array, it overwrites it when actually it should add more items (objects) instead of over writing? Where could I be going wrong?

The array public playlist = []; is being shared across components via a service and that is the array that the objects are getting pushed to.

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

Upvotes: 0

Views: 98

Answers (1)

Plochie
Plochie

Reputation: 4117

You are seeing overriding behavior, which is correct as per your given code. As while saving in localstore you are getting what is already stored in localstore then assigning it to playlist and again saving the playlist stored in localstore.

You need to save the playlist first in localstore and then by getting it assign to class level playlist.

savePlyaList function should be as follows,

Playlist.service.ts

savePlaylist() {
    // first save the data 
    localStorage.setItem('playlist', JSON.stringify(this.playlist));
    // get what is saved afterwords
    this.playlist = JSON.parse(localStorage.getItem('playlist'));
    console.log('Saved', this.playlist);
}

Upvotes: 1

Related Questions