Angular2: extract array element form http.get response

1.2k Views Asked by At

Angular2 is so much fun! (end of Sarcasm)

This particular plunker is successful in extracting a very specific element from the array and then is able to display it into the templateUrl. Generally speaking is really easy to display data in the template.

Unfortunately that is not my issue. What I need to do is get a value from dataService / Injectable and turn it into a variable and then pass that variable into chart program. Basically, I need something like this: console.log(last);

   //a simple json data component
   import {Component, View} from 'angular2/angular2'
   import {DataService} from './dataService'

   @Component({
    selector: 'my-data',
  templateUrl: 'src/template.html'
})
export class Data {
  constructor(dataService:DataService) {
    dataService.dataObser
      .subscribe(dataObj => {
        this.last = dataObj.person.last;
        this.dataObj = dataObj;
      });
      console.log("this is what I'm looking for " + this.last);
  }
}

I will then take the variable and pass into chartData, as laid out in this question. That is why I need capture this response from the json and turn it into a variable. I'm think this shouldn't be that difficult?

1

There are 1 best solutions below

2
Günter Zöchbauer On
dataService.dataObser
  .subscribe(dataObj => {
    this.last = dataObj.person.last;
    this.dataObj = dataObj;
  });
  // this line is executed before the first `dataObject` event arrives.
  console.log("this is what I'm looking for " + this.last);

If there is only one event to be expected move this line inside the .subscribe() callback, otherwise add a complete callback

dataService.dataObser
  .subscribe(dataObj => {
    this.last = dataObj.person.last;
    this.dataObj = dataObj;
  }, 
  (_) => {}, 
  () => {
    console.log("this is what I'm looking for " + this.last);
  });
  // this line is executed before the first `dataObject` event arrives.