jelscript jelscript - 7 months ago 67
Javascript Question

Get item from Observable in Angular 2 with Typescript

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:

getItems() {
this.observableData = this._http.get('json_path/')
.map(res => res.json())
.do(val => {
this.result = val;
this.observableData = null;
})
.share();
return this.observableData;
}


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]);

Answer

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()

Comments