【发布时间】:2018-06-19 18:56:06
【问题描述】:
我正在做一个项目,我希望在其中拥有 JSON 文件资产文件夹。我创建服务和组件。 1-资产文件夹中的我的 JSON 文件
data.json
[
{
"Date" : "10/09/2017",
"ID" : "1",
"Color" : "Orange",
}, {
"Date" : "10/11/2017",
"ID" : "2",
"Color" : "Green",
}
]
我为读取数据的服务创建了一个服务,将其存储在 JSON 格式的数据变量中。将 JSON 文件保存在 assets 文件夹中很重要,因为这样很容易访问它。
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);
}
);
}
}
上述服务工作正常,并在控制台中显示 JSON 数据。 现在的
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();
}
}
它在控制台中显示 JSON 数据,但如何在 HTML 中显示数据。我尝试了不同的方法,但对我没有任何效果。
如果我找到任何解决方案,我会更新问题。如果有人已经知道如何解决这个问题,我会很高兴。
【问题讨论】:
-
您尝试过什么以 HTML 格式显示数据?什么不起作用?
标签: javascript json angular rest typescript