0

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.

1
  • What have you tried to display the data in HTML? What does not work? Commented Jan 10, 2018 at 15:02

2 Answers 2

3

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

     );
    };
  }

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

1 Comment

@ziaullahzia no problem. make sure to check as answer if this helped :D
2

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"
  }
]

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.