在我的Angular应用程序中。我有一个数组,它使对象从rest api推送到它。该数组称为playlist=[]
,并通过称为播放列表服务的服务在各个组件之间共享。该服务中还有两个功能。一种将播放列表保存到localStorage
,另一种从localStorage
获取。所以发生的事情是当我保存播放列表时,它可以保存到本地存储中。即使我刷新它们,它们仍然在本地存储中。因此,当我在单个会话中使用我的应用程序(不刷新浏览器)时,savePlaylist()
方法将对象添加到播放列表数组中,但它不会覆盖它们(很好)。但是,如果刷新页面后添加项目,然后保存-这些项目将被添加到已保存的本地存储中时,它们将被覆盖。这可能吗?这与sessionStorage有关吗?有任何想法吗?到目前为止,我的代码是:
playlist.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'));
}
}
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);
}
constructor() {
}
}
播放列表.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.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>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of list.playlist">
<td><img src="{{user.artworkUrl60}}"></td>
<td>{{user.artistName}}</td>
<td>{{user.collectionName}}</td>
<td>{{user.primaryGenreName}}</td>
<td>{{user.collectionPrice}}</td>
</tr>
</tbody>
</table>
</div>
<app-footer></app-footer>