【发布时间】:2020-04-30 12:37:55
【问题描述】:
所以我有服务,也有功能,我想使用 observable 而不是经典功能。
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。
【问题讨论】:
-
我不清楚你想如何/在哪里使用 observables。我假设你想看的是
Subjects,但如果没有更好的描述就很难知道。你想用 observable 替换哪个函数? -
如果使用 'rxjs' 运算符 of 你会得到一个 observable,例如
return of([1,2,3,4]), -
我希望所有函数都替换为 observables。
-
@MladenNikolić 我知道您认为您对此事的描述很清楚,但事实并非如此。再说一遍也无助于我们理解它。拜托,您能否添加一个您想要最终得到的代码示例,给我们一个方向
标签: angular rxjs observable subscribe