0

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?

Community
  • 1
  • 1
Chad
  • 643
  • 2
  • 11
  • 22

1 Answers1

0
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.
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • So that makes sense, however I dropped the new code in the plnker and it doesn't seem echoing out in the console. I'm getting a `EXCEPTION: TypeError: l_dataObj2 is undefined in [null]` – Chad Feb 01 '16 at 19:50
  • I updated my answer. I don't use TS myself (only Dart) and are not sure about the exact syntax. See also this alternate syntax https://github.com/angular/angular/blob/4e5cd1e558503aec87dd95e59337b31f261c941f/modules/angular2/src/facade/async.ts#L40 where the arguments are passed as object. Mixing the two seems not to work. – Günter Zöchbauer Feb 01 '16 at 20:19