【问题标题】:Push element in observable Angular 9在可观察的 Angular 9 中推送元素
【发布时间】:2020-08-28 11:43:50
【问题描述】:

我有一个可观察对象,该可观察对象是存储在本地存储中的一组对象(视频)。 我在服务中有这样的“功能”,用于将新视频推送到数组中: 视频是一个界面

    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 之前,我使用经典的常量和函数并且工作得很好,现在我遇到了 observables 的问题。有人告诉我,我需要以某种方式订阅管道,但我无法在任何地方找到如何做到这一点。 Observables 对我来说是新事物,而且非常令人困惑。

【问题讨论】:

  • 嘿,我的回答解决了你的问题吗?

标签: angular rxjs observable angular9 subscribe


【解决方案1】:

如果目标是更新videoList 的值,您可以这样做:

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

这简化了上述setVideo 方法,无需使用pipe()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-26
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    相关资源
    最近更新 更多