最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get item from Observable in Angular 2 with Typescript - Stack Overflow

programmeradmin3浏览0评论

I am trying to get an item from an observable in Angular 2 that's provided by a service. So far I can subscribe to the observable and see the contents in the console but cannot filter out an item by it's ID. I have tried the following below but get a blank screen. Any tips appreciated.

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;
}

ponent.ts:

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

I am trying to get an item from an observable in Angular 2 that's provided by a service. So far I can subscribe to the observable and see the contents in the console but cannot filter out an item by it's ID. I have tried the following below but get a blank screen. Any tips appreciated.

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;
}

ponent.ts:

let id = this._routeParams.get('id');
this._jobService.getJobs().map(jobs => jobs.filter(item => item.id === id).subscribe(job => this.job = job)[0]);
Share Improve this question edited Apr 10, 2017 at 21:49 skyscript asked Apr 25, 2016 at 17:10 skyscriptskyscript 1753 silver badges12 bronze badges 2
  • Is this intentional. You posted the getItems() method and then use the getJobs() method below. – Günter Zöchbauer Commented Apr 25, 2016 at 17:11
  • Ah, that was a mistake. They should both be either getItems() or getJobs(). Thanks – skyscript Commented Apr 25, 2016 at 21:07
Add a ment  | 

1 Answer 1

Reset to default 6

I think you want something like:

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

You can't subscribe to the result of jobs.filter()

发布评论

评论列表(0)

  1. 暂无评论