簡體   English   中英

可觀察 Angular 9 中的推元素

[英]Push element in observable Angular 9

我有一個可觀察對象,該可觀察對象是存儲在本地存儲中的一組對象(視頻)。 我在服務中有這樣的“功能”,用於將新視頻推送到數組中:視頻是一個接口

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

在其他組件中,我稱之為推送新的 object(視頻),如下所示:

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 的問題。 有人告訴我,我需要以某種方式訂閱 pipe,但我找不到任何方法。 Observables 對我來說是新的並且非常令人困惑。

如果目標是更新videoList的值,您可以這樣做:

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

這簡化了上面的setVideo方法,而不需要使用pipe()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM