In the midst of a project, I found myself in need of a JSON file stored within an assets folder. To accomplish this, I created a service and component. 1- The JSON file resides in the assets folder.
data.json
[
{
"Date" : "10/09/2017",
"ID" : "1",
"Color" : "Orange",
}, {
"Date" : "10/11/2017",
"ID" : "2",
"Color" : "Green",
}
]
To access and store the data in JSON format, I developed a service that retrieves the data from the JSON file in the assets folder. This setup ensures easy accessibility to the JSON file.
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 service functions as intended, displaying the JSON data in the console. Moving on to 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();
}
}
While the JSON data is successfully displayed in the console, I encountered difficulties when attempting to display it in HTML. Various approaches were explored but none yielded the desired outcome.
I will continue trying to find a solution and update this question accordingly. Any assistance in resolving this matter would be greatly appreciated.