Observable代替功能角8 9

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

所以我有服务,并且我有功能,我想使用可观察的而不是经典的功能。

  export class VideoServiceService {
  videoList = JSON.parse(localStorage.getItem('videos') || '[]');
  safeURL2: string;
  safeURL: any;

  constructor(public dialog: MatDialog, private sanitizer: DomSanitizer) { }

  getVideos() {
    return this.videoList;
  }

  setVideo(video: object) {
    this.videoList.push(video);
    localStorage.setItem('videos', JSON.stringify(this.videoList));
  }

  deleteVideo(index: number) {
    this.videoList = this.videoList.filter(c => c.ID !== index);
    localStorage.setItem('videos', JSON.stringify(this.videoList));
  }

  getVideo(index: number) {
   return this.videoList.find(c => c.ID === index);
  }

  getURL(data: any) {
    this.safeURL2 = data.replace('https://www.youtube.com/watch?v=', 'https://www.youtube.com/embed/');
    this.safeURL = this.sanitizer.bypassSecurityTrustResourceUrl(this.safeURL2);
    return this.safeURL;
  }

}

我在其他组件中都有调用功能的按钮,例如用于将视频添加到列表,从列表中删除视频,从列表中编辑视频的表单等。例如:在列表组件中,我具有编辑按钮,可以调用编辑功能:

editDialog(id: number): void {
    const dialogRef = this.dialog.open(AddVideoFormComponent, {data: id} );
    dialogRef.afterClosed().subscribe(data => {
      if (data) {
        this.videoService.deleteVideo(id);
        data.id = this.index++;
        this.videoService.setVideo(data);
        this.dataSource = this.videoService.getVideos();
        this.table.renderRows();
      }
    });
  }

所以我在这里使用经典功能。没有太多关于此的教程,仅针对HTTP,但在这种情况下我不需要。我只需要使用observable而不是function并调用它,然后传递ID。

angular rxjs observable subscribe
1个回答
0
投票

您可以模拟可观察的插入经典函数,例如:

import { of } from 'rxjs';
...
getVideo(index: number) {
  return of(this.videoList.find(c => c.ID === index));
}

OR

import { Observable} from 'rxjs';
...
getVideo(index: number) {
  return new Observable((o) => {
    o.next(this.videoList.find(c => c.ID === index));
    o.complete();
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.