Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

getJobs() {
  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]);
like image 504
skyscript Avatar asked Apr 25 '16 17:04

skyscript


1 Answers

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

like image 70
Günter Zöchbauer Avatar answered Sep 20 '22 04:09

Günter Zöchbauer