臨摹微笑
2023-09-28 16:07:29
我能夠從我的應(yīng)用程序中的 REST API 獲取數(shù)據(jù),我能夠?qū)?shù)據(jù)打印到控制臺(tái),但不知道如何顯示在 html 上,有人可以幫助我嗎?應(yīng)用程序組件.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}); }}應(yīng)用程序組件.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貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
嘗試設(shè)置對(duì) Employee 的響應(yīng)類型并將其添加到數(shù)組中,如下所示:
this.http.get("http://localhost:8080/api/all").subscribe(
(response: Employee[]) =>{
this.employees.push(...response);
});

繁花如伊
TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊
因?yàn)槟陧憫?yīng)中獲取數(shù)組并且它來自員工類型,所以應(yīng)該是這樣的:
this.http.get("http://localhost:8080/api/all").subscribe(
(response: Array<Employee>) =>{
this.employees = response;
});
添加回答
舉報(bào)
0/150
提交
取消