Angular2对象未定义

时间:2015-09-28 21:03:50

标签: typescript angular

访问服务组件的对象时获取“对象未定义”。但硬编码下面的数据到javaScript变量工作正常,并显示对象类型“对象数组”

Data.json

[
      {
        "id": 1,
        "name": "Malad",
        "gateway": "10.10.100.1",
        "device": "cisco"
      }, {
        "id": 2,
        "name": "Kandhivali",
        "gateway": "222.30.100.1",
        "device": "Juniper"
      }
]

DataService.ts

import {Injectable} from 'angular2/angular2'
import {Http} from 'angular2/http';

@Injectable()
export class DataService {

  tdata = [
  {
    "id": 1,
    "name": "Malad",
    "gateway": "10.10.100.1",
    "device": "cisco"
  }, {
    "id": 2,
    "name": "Kandhivali",
    "gateway": "222.30.100.1",
    "device": "Juniper"
  }
];

  data;
  constructor(http: Http){
    http.get('Data.json')
    .toRx()
    .map(res => res.json())
    .subscribe(res => this.data= res);
  }

}

DataPage.ts

import {Component, View, CORE_DIRECTIVES} from 'angular2/angular2'
import {DataService} from './DataService'

@Component({
  selector: 'DataPage'
})
@View({
  template: `
{{data | json}}  //Working //object Array
<br>
{{data | json}}  //Not Wokring // object Undefined //No data :(
`


directives: [CORE_DIRECTIVES]
})

export class DataPage{
  query;
  tquery;
    constructor( public dataService:DataService){

       this.query = dataService.data; // object Undefined
       this.tquery = dataService.tdata; //object Array

  }
}

1 个答案:

答案 0 :(得分:2)

那是因为你异步获得data。您不能期望服务在您调用时返回值,因此您应该在服务中返回Observable并在组件中订阅它。

在您的服务中

constructor(http: Http){
    this.http = http;
}
myData() {
  return this.http.get('Data.json')
     .toRx()
     .map(res => res.json());
}

在您的组件中

constructor( public dataService:DataService){

       dataService.myData().subscribe(res => this.query = res);

       this.tquery = dataService.tdata; //object Array
  }

并将您的观点更改为此

@View({
    template: `
     {{tquery| json}}
     <br>
     {{query | json}}
    `

这是一个复制品:http://plnkr.co/edit/BeMpYR?p=preview