所以我有服务和函数,我想使用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。
发布于 2020-05-01 00:55:15
您可以模拟可观察的实例经典函数,例如:
import { of } from 'rxjs';
...
getVideo(index: number) {
return of(this.videoList.find(c => c.ID === index));
}或
import { Observable} from 'rxjs';
...
getVideo(index: number) {
return new Observable((o) => {
o.next(this.videoList.find(c => c.ID === index));
o.complete();
});
}https://stackoverflow.com/questions/61523564
复制相似问题