使用Typescript从Angular 2中的Observable获取项目

sky*_*ipt 4 javascript typescript typescript1.8 angular

我试图从一个服务提供的Angular 2中的一个observable中获取一个项目.到目前为止,我可以订阅observable并查看控制台中的内容,但不能通过它的ID过滤掉项目.我在下面尝试了以下内容,但得到一个空白屏幕.任何提示赞赏.

service.ts:

getJobs() {
  this.observableData = this._http.get('json_path/')
      .map(res => res.json())
      .do(val => {
        this.result = val;
        this.observableData = null;
      })
      .share();
  return this.observableData;
}
Run Code Online (Sandbox Code Playgroud)

component.ts:

let id = this._routeParams.get('id');
this._jobService.getJobs().map(jobs => jobs.filter(item => item.id === id).subscribe(job => this.job = job)[0]);
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 5

我想你想要的东西:

let id = this._routeParams.get('id');
this._jobService.getJobs().map(jobs => {
  return jobs.filter(item => item.id === id)[0];
}).subscribe(job => this.job = job));
Run Code Online (Sandbox Code Playgroud)

你不能订阅结果 jobs.filter()

  • 我通过将 [0] 索引移动到 `jobs.filter()` 而不是 `.subscribe()` 的结果来使其工作。`this._jobService.getJobs().map(jobs => { return jobs.filter(item => item.id === id)[0]; }).subscribe(job => this.job = job); ` (2认同)