【问题标题】:How do I send REST response to html in angular?如何以角度向 html 发送 REST 响应?
【发布时间】: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


【解决方案1】:

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

    this.http.get("http://localhost:8080/api/all").subscribe(
    (response: Employee[]) =>{
      this.employees.push(...response);
    });

【讨论】:

  • 我已经添加了上面的代码,但是在控制台中它说 ERROR TypeError: Cannot read property 'id' of undefined。你能告诉我 app.component.html 有什么问题吗?
  • 这与他描述的响应不兼容。响应是一个员工数组,员工对象也是如此。在这里,您正在尝试将数组推入数组。
  • 然后:(响应:Employee[])=>{ this.employees.push(...response);
  • @misha1109 这可行,但不是最优雅的方式。
  • @vladkatz 似乎与您的答案几乎相同,我更喜欢推送到数组以防 http 请求不仅发生在 onInit 上
【解决方案2】:

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

this.http.get("http://localhost:8080/api/all").subscribe(
(response: Array<Employee>) =>{
  this.employees = response;
});

【讨论】:

  • 非常感谢 :) 非常感谢您的工作。
  • 任何时候。这应该在没有强制转换的情况下工作,但您应该始终检查来自 API 的接收对象与组件/服务内分配的对象之间的可组合性。如果您尝试将数组放入常规对象中,则会出现错误,反之亦然
猜你喜欢
  • 2018-08-11
  • 1970-01-01
  • 2017-09-07
  • 2020-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-06
相关资源
最近更新 更多