首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Observable代替函数angular 8 9

Observable代替函数angular 8 9
EN

Stack Overflow用户
提问于 2020-04-30 20:37:56
回答 1查看 70关注 0票数 0

所以我有服务和函数,我想使用observable而不是经典函数。

代码语言:javascript
复制
  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;
  }

}

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

代码语言:javascript
复制
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。

EN

回答 1

Stack Overflow用户

发布于 2020-05-01 00:55:15

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

代码语言:javascript
复制
import { of } from 'rxjs';
...
getVideo(index: number) {
  return of(this.videoList.find(c => c.ID === index));
}

代码语言:javascript
复制
import { Observable} from 'rxjs';
...
getVideo(index: number) {
  return new Observable((o) => {
    o.next(this.videoList.find(c => c.ID === index));
    o.complete();
  });
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61523564

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档