ZiaUllahZia
ZiaUllahZia

Reputation: 1142

How to fetch json data from JSON file in angular 4

I am working on one project in which I want to have JSON file assets folder. I create service and component. 1- My JSON file in assets folder

data.json

[ 
 {
    "Date" : "10/09/2017",
    "ID" : "1",
    "Color" : "Orange",
  }, {
    "Date" : "10/11/2017",
    "ID" : "2",
    "Color" : "Green",
  }
]

I created a service for that which read the data store it in data variable in JSON formate. It is important to keep the JSON file in assets folder because it will be easily accessible then. The

data.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class DataService {

  constructor(private http: Http) {   }

  fetchData() {
    return this.http.get('assets/data/data.json').map(
      (Response)=>Response.json()
    ).subscribe(
      (data) => {
        console.log(data);
      }

    );
  }

}

The above service works fine and displays the JSON data in the console. Now the

data.component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../../services/data.service';
import { DataTablesModule } from 'angular-datatables';

@Component({
  selector: 'app-data',
  templateUrl: './data.component.html',
  styleUrls: ['./data.component.css']
})
export class DataComponent implements OnInit {

  constructor(private DataResponse: DataService ) { }

  ngOnInit() {
    this.DataResponse.fetchData();
  }

}

It displays the JSON data in the console but How to display the data in HTML. I tried different approaches but nothing works for me.

I will update the question if I found any solution. I will be very happy if someone already know how to solve this.

Upvotes: 0

Views: 3998

Answers (2)

Ahmad Alfy
Ahmad Alfy

Reputation: 13371

The JSON file you provided is invalid JSON format. Unlike JavaScript arrays and objects, you cannot have trailing commas in the last items.

It should be:

[ 
 {
    "Date" : "10/09/2017",
    "ID" : "1",
    "Color" : "Orange"
  }, {
    "Date" : "10/11/2017",
    "ID" : "2",
    "Color" : "Green"
  }
]

Upvotes: 2

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41387

instead of subscribing in the service, subscribe inside the component.In service return the observable.

 fetchData() {
    return this.http.get('assets/data/data.json').map(
      (Response)=>Response.json()
    )
  }

Now, subscribe inside the component and bind the data variable to the HTML

export class DataComponent implements OnInit {
  data:any;

  constructor(private DataResponse: DataService ) { }

  ngOnInit() {
    this.DataResponse.fetchData().subscribe(
      (data) => {
       this.data = data;
      }

     );
    };
  }

}

Upvotes: 3

Related Questions