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