所以我有服务并且有功能,我想使用可观察的而不是经典的功能。
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。
答案 0 :(得分: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();
});
}