eddie eddie -4 years ago 221
TypeScript Question

Angular2 HTTP TypeScript Json

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


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";

selector: 'my-app'

template: `

<th>Region Id</th>
<tr *ngFor="#item of myData">
export class AppComponent {

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";

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())
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.

Answer Source

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download