Angular2:从http.get响应中提取数组元素

时间:2016-02-01 19:33:42

标签: javascript angular typescript1.6 angular2-services

Angular2非常有趣! (讽刺结束)

此特定plunker成功从数组中提取非常特定的元素,然后能够将其显示到templateUrl中。一般来说,在模板中显示数据非常容易。

不幸的是,这不是我的问题。我需要做的是从dataService / Injectable获取一个值并将其转换为变量,然后将该变量传递给图表程序。基本上,我需要这样的东西: 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);
  }
}

然后我将获取变量并传递给chartData,如此question中所示。这就是为什么我需要从json捕获这个响应并将其转换为变量。我觉得这不应该那么难吗?

1 个答案:

答案 0 :(得分: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);

如果预计只有一个事件,请在.subscribe()回调中移动此行,否则添加complete回调

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.