推送元素在observable Angular 9中

问题描述 投票:-1回答:1

我有一个observable,这个observable是一个存储在本地存储中的对象(视频的)数组。我在服务中设置了这样的 "函数",用于将一个新的视频推送到数组中。视频是一个接口

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

但这行不通,我知道这是我的错误。在使用observable之前,我使用了经典的常量和函数,工作得很好,但现在我在使用observable时遇到了问题。有人告诉我,我需要以某种方式在管道上进行订阅,但我在任何地方都找不到如何做到这一点。观测值对我来说是个新事物,而且非常混乱。

angular rxjs observable angular9 subscribe
1个回答
0
投票

如果目标是更新 videoList,这是你可以做的代替。

setVideo(video: Video) {
  const updatedValue = [
    ...this.videoList.value,
    video,
  ];
  this.videoList.next(updatedValue)
  localStorage.setItem('videos', JSON.stringify(updatedValue));
}

这样可以简化上面的内容 setVideo 方法,而不需要使用 pipe().

© www.soinside.com 2019 - 2024. All rights reserved.