我有一个可观测的,可观测的是存储在本地存储中的一系列对象(视频)。我有这样的“功能”来将一个新的视频推入数组:视频是一个接口。
videoList: BehaviorSubject<Video[]> = new BehaviorSubject(JSON.parse(localStorage.getItem('videos') || '[]'));
setVideo(video: Video): Observable<Video> {
return this.videoList.pipe(
switchMap(videoList => {
videoList.push(video);
localStorage.setItem('videos', JSON.stringify(videoList));
this.videoList.next(videoList);
return of(video);
})
);
}在另一个组件中,我称之为它来推送一个新对象(视频),如下所示:
openDialog(): void {
const dialogRef = this.dialog.open(AddVideoFormComponent);
dialogRef.afterClosed().subscribe(data => {
data.id = this.index++;
this.videoService.setVideo(data);
this.table.renderRows();
});
}但这行不通,我知道这是我的错。在可观察之前,我使用了经典的常量和函数,并且工作得很好,现在我在可观测值方面遇到了麻烦。有人告诉我,我需要订阅一个烟斗,但我找不到如何做到这一点。可观察性对我来说是新的,而且非常令人困惑。
发布于 2020-05-12 15:06:39
如果目标是更新videoList的值,则可以这样做:
setVideo(video: Video) {
const updatedValue = [
...this.videoList.value,
video,
];
this.videoList.next(updatedValue)
localStorage.setItem('videos', JSON.stringify(updatedValue));
}这简化了上面的setVideo方法,而不需要使用pipe()。
https://stackoverflow.com/questions/61755024
复制相似问题