为了账号安全,请及时绑定邮箱和手机立即绑定

如何以角度方式向 html 发送 REST 响应?

如何以角度方式向 html 发送 REST 响应?

临摹微笑 2023-09-28 16:07:29
我能够从我的应用程序中的 REST API 获取数据,我能够将数据打印到控制台,但不知道如何显示在 html 上,有人可以帮助我吗?应用程序组件.tsimport { 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});      }}应用程序组件.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>
查看完整描述

2 回答

?
慕仙森

TA贡献1827条经验 获得超7个赞

尝试设置对 Employee 的响应类型并将其添加到数组中,如下所示:


    this.http.get("http://localhost:8080/api/all").subscribe(

    (response: Employee[]) =>{

      this.employees.push(...response);

    });


查看完整回答
反对 回复 2023-09-28
?
繁花如伊

TA贡献2012条经验 获得超12个赞

因为您在响应中获取数组并且它来自员工类型,所以应该是这样的:


this.http.get("http://localhost:8080/api/all").subscribe(

(response: Array<Employee>) =>{

  this.employees = response;

});


查看完整回答
反对 回复 2023-09-28
  • 2 回答
  • 0 关注
  • 57 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信