【发布时间】:2021-03-15 03:33:12
【问题描述】:
我能够在我的应用程序中从 REST API 获取数据,我能够将数据打印到控制台上,但不知道如何在 html 上显示,有人可以帮我吗?
App.component.ts
import { HttpClient } from '@angular/common/http';
import { Component, Inject } from '@angular/core';
import { Employee } from './employee';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'emp-data-example';
employees:Employee[]=[];
constructor(@Inject(HttpClient) private http:HttpClient){
}
ngOnInit(){
this.http.get("http://localhost:8080/api/all").subscribe(
response=>{
this.employees=response; // here is error because response is an Object and employees is an array
});
//resp.subscribe((data)=>{this.employees=data});
}
}
app.component.html
<div>
<table border="1">
<tr>
<th>Emp Id</th>
<th>Emp Name</th>
<th>Salary</th>
</tr>
<tr ngFor="let employee of employees">
<td>{{employee.id}}</td>
<td>{{employee.name}}</td>
<td>{{employee.department}}</td>
<td>{{employee.salary}}</td>
</tr>
</table>
</div>
【问题讨论】:
-
试试这个
this.employees=[response]; -
没有它的说法,“对象”类型可以分配给极少数其他类型。您的意思是改用“任何”类型吗? “对象”类型缺少“员工”类型的以下属性:id、姓名、部门、薪水(2696)
-
那么你能展示你的响应对象吗?
-
[{"id":0,"name":"sudheer","department":"IT","salary":12344.0},{"id":23,"name": "kumar","department":"ECE","salary":12345.0}] 是我从 REST 得到的响应,并且仅在控制台上打印。
-
如果这是响应,您的代码应该可以工作。但请确保您的
Employee模型具有属性
标签: javascript html node.js angular