Search code examples
jsontypescriptangular2-http

Angular2 HTTP TypeScript Json


I have one locally stored "region.json" file like this:

{
  "regionId":1, 
  "region":"CAN"
},
{
  "regionId":2, 
  "region":"CEN"
}

I have "enviroment-app.component.ts" file which like this :

import {Component, View, CORE_DIRECTIVES, FORM_DIRECTIVES} from "angular2/core";
import {HTTPTestService} from "./http-test.service";

@Component({
   selector: 'my-app'
})

@View({
  template: `

<table>
    <thead>
        <th>Region Id</th>
        <th>Region</th>
    </thead>
    <tbody>
        <tr *ngFor="#item of myData">
            <td>{{item.regionId}}</td>
            <td>{{item.Region}}</td>
        </tr>
    </tbody>
</table>`
  })
export class AppComponent {
myData:any;
}

and I have "http-test.service.ts" file which look like :

import {Injectable} from "angular2/core";
import {Http} from "angular2/http";
import 'rxjs/add/operator/map';
import {Headers} from "angular2/http";
import {AppComponent} from "./environment_app.component";

@Injectable()
export class HTTPTestService{
constructor (private _http: Http){}

this.myData = {region:[]};
get("./region.json") {
   return this._http.get("./region.json", { headers: headers })
        .map(res => res.json())
        .subscribe
         (
         data => {
            this.myData = data;
         });
}
}

In the Front-End, I am only able to print the header as enter image description here

I want to fetch all the json data

What I am doing wrong?? Please, Any help appreciated,

Thanks in advance.


Solution

  • The response of the json goes in a variable named myData. This variable is is a member of the service, and not your AppComponent class. However,

    *ngFor="#item of myData"

    In the above *ngFor, this myData variable is a part of your AppComponent class which was never filled.

    Do this:

    1. Make a function, as you did in your service that returns json data after reading the file.
    2. Return that data back to AppComponent.
    3. Assign that to myData in AppComponent.