[英]How to fetch json data from JSON file in angular 4
我正在一個項目中,我要擁有JSON文件資產文件夾。 我創建服務和組件。 1-資產文件夾中的我的JSON文件
[
{
"Date" : "10/09/2017",
"ID" : "1",
"Color" : "Orange",
}, {
"Date" : "10/11/2017",
"ID" : "2",
"Color" : "Green",
}
]
我為讀取數據的服務創建了一個服務,將其存儲在JSON formate的data變量中。 將JSON文件保存在Assets文件夾中非常重要,因為這樣可以輕松訪問它。 的
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);
}
);
}
}
上面的服務工作正常,並在控制台中顯示JSON數據。 現在
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();
}
}
它在控制台中顯示JSON數據,但如何在HTML中顯示數據。 我嘗試了不同的方法,但對我沒有用。
如果找到任何解決方案,我將更新問題。 如果有人已經知道如何解決這個問題,我將感到非常高興。
而不是訂閱服務,而是在組件內部進行訂閱。在服務中,返回可觀察對象。
fetchData() {
return this.http.get('assets/data/data.json').map(
(Response)=>Response.json()
)
}
現在,在組件內部訂閱並將data
變量綁定到HTML
export class DataComponent implements OnInit {
data:any;
constructor(private DataResponse: DataService ) { }
ngOnInit() {
this.DataResponse.fetchData().subscribe(
(data) => {
this.data = data;
}
);
};
}
}
您提供的JSON文件是無效的JSON格式。 與JavaScript數組和對象不同,您在最后一項中不能包含結尾逗號。
它應該是:
[
{
"Date" : "10/09/2017",
"ID" : "1",
"Color" : "Orange"
}, {
"Date" : "10/11/2017",
"ID" : "2",
"Color" : "Green"
}
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.