以角度显示json文件中的数据
这是我的以角度显示json文件中的数据,json,angular7,Json,Angular7,这是我的home.component.ts文件: import { Component, OnInit } from '@angular/core'; import {HttpClient, HttpResponse, HttpHeaders} from '@angular/common/http'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./hom
home.component.ts
文件:
import { Component, OnInit } from '@angular/core';
import {HttpClient, HttpResponse, HttpHeaders} from '@angular/common/http';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private http: HttpClient) { }
cars=[];
fetchData=function(){
this.http.get("http://localhost:3000/cars").subscribe(
(res:Response)=>{
this.cars=res.json();
}
)
}
ngOnInit() {
this.fetchData();
}
}
<h1>Cars</h1>
<table>
<th>Id</th>
<th>Brand</th>
<th>Model</th>
<tr *ngFor="let car of cars">
<td>{{car.id}}</td>
<td>{{car.brand}}</td>
<td>{{car.model}}</td>
</tr>
</table>
{
"cars": [
{
"id": 1,
"brand": "Seat",
"model" : "Leon"
},
{
"id": 2,
"brand": "Mercedes",
"model" : "AMG"
}
]
}
home.component.html
文件:
import { Component, OnInit } from '@angular/core';
import {HttpClient, HttpResponse, HttpHeaders} from '@angular/common/http';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private http: HttpClient) { }
cars=[];
fetchData=function(){
this.http.get("http://localhost:3000/cars").subscribe(
(res:Response)=>{
this.cars=res.json();
}
)
}
ngOnInit() {
this.fetchData();
}
}
<h1>Cars</h1>
<table>
<th>Id</th>
<th>Brand</th>
<th>Model</th>
<tr *ngFor="let car of cars">
<td>{{car.id}}</td>
<td>{{car.brand}}</td>
<td>{{car.model}}</td>
</tr>
</table>
{
"cars": [
{
"id": 1,
"brand": "Seat",
"model" : "Leon"
},
{
"id": 2,
"brand": "Mercedes",
"model" : "AMG"
}
]
}
我启动了json服务器并编译了项目。结果就是没有获取数据的结果。json服务器正在3000端口上侦听,我使用的是angular 7.0.3版本。有人能帮我吗?试试这个:
const fs = require('fs');
let rawdata = fs.readFileSync('cars.json');
let cars = JSON.parse(rawdata);
或
这解决了我的问题。谢谢您的帮助。您需要设置
this.cars=res.cars代码>无需再次解析,默认情况下返回json