如何从localStorage Angular中的数组中删除单个对象

时间:2019-11-26 00:18:22

标签: javascript angular typescript local-storage

我想从localStorage中的数组中添加一个删除对象。到目前为止,我删除的是整个数组,而不是单个对象,下面是我的service.ts文件

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

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

  public playlist = [];

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

   deleteSongFromPlaylist(collectionId: number) {
    this.getPlaylist()
    const songIndex = this.playlist.findIndex(s => s.collectionId === collectionId)
    if (songIndex > -1) {
      this.playlist.splice(songIndex, 1)
      this.savePlaylist();
    }
  }

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

要使用数组将项目添加到数组中,请执行以下操作:

component.ts

  addSongToPlaylist(itunes) {
    this.list.playlist.push(Object.assign({}, itunes));
    this.list.savePlaylist();
    console.log('Playlist - ', this.list.playlist);
  }

component.html

<div class="col-md-2 mb-5 col-lg-2 col-sm-12">
   <a target="_blank"><button type="button" class="btn btn-light btn-lg float-right"
     (click)="addSongToPlaylist(itunes)"><fa-icon [icon]="faPlus"></fa-icon>
</button></a>

播放列表.ts

import { Component, OnInit } from '@angular/core';
import { PlaylistService } from '../../../services/playlist.service';
import { faSave } from '@fortawesome/free-solid-svg-icons';
import { faMinus } 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;
  faMinus = faMinus;
  collectionId: number;

  p: number = 1;

  constructor(private list: PlaylistService) { }

  remove() {
    this.list.deleteSongFromPlaylist(this.collectionId);
  }

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

  }
}

playlist.html

<app-header></app-header>
<div class="container">
  <table class="table mt-3 mb-3">
    <thead class="thead-light">
      <tr>
        <th>Artwork</th>
        <th>Artist</th>
        <th>Title</th>
        <th>Genre</th>
        <th>Price</th>
        <th>Listen</th>
        <th>Edit</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let user of list.playlist | paginate: { itemsPerPage: 5, currentPage: p }">
        <td><img src="{{user.artworkUrl60}}"></td>
        <td>{{user.artist}}</td>
        <td>{{user.Name}}</td>
        <td>{{user.GenreName}}</td>
        <td>{{user.Price}}</td>
        <td><a href="{{user.collectionViewUrl}}" target="_blank">Music</a></td>

        <td><a target="_blank"><button type="button" class="btn btn-sm btn-danger"
          (click)="remove()">
          <fa-icon [icon]="faMinus">
          </fa-icon>
        </button></a></td>
      </tr>
    </tbody>
  </table>
  <div class="table-pagination mb-5">
      <pagination-controls (pageChange)="p = $event" class="my-pagination"></pagination-controls>
    </div>
</div>

<app-footer></app-footer>

1 个答案:

答案 0 :(得分:1)

您需要获取数组,然后再次保存,这需要您有一种方法来标识要删除的播放列表中的项目。

因为歌曲具有某种collectionId属性...

deleteSongFromPlaylist(collectionId: number) {
  this.getPlaylist()
  const songIndex = this.playlist.findIndex(s => s.collectionId === collectionId)
  if (songIndex > -1) {
    this.playlist.splice(songIndex, 1)
    this.savePlayList()
  }
}

调用此函数将类似于:

<a target="_blank"><button type="button" class="btn btn-sm btn-danger"
      (click)="remove(user.collectionId)">

remove(collectionId: number) {
  this.list.deleteSongFromPlaylist(collectionId);
}