0

Getting "object undefined" while accessing object of Service Component. But hard coded below data to javaScript variable working fine and shows object type "object Array"

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 Answer 1

2

That's because you are getting data asynchronously. You can't expect the service to return the value when you call it, so you should return the Observable in your service and subscribe to it in your component.

In your service

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

In your component

constructor( public dataService:DataService){

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

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

and change your view to this

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

Here's a repro : http://plnkr.co/edit/BeMpYR?p=preview

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.