我得到了这个api“ http://dummy.restapiexample.com/api/v1/employees” 然后我尝试将其与* ngFor一起使用,但是会发生此问题 “错误错误:找不到类型为'object'的其他支持对象'[object Object]'。NgFor仅支持绑定到Iterables,例如数组。”
app.component.ts
import { Component } from '@angular/core';
import { HttpClient } from "@angular/common/http";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
employes;
constructor(private http : HttpClient) {
this.http.get('http://dummy.restapiexample.com/api/v1/employees').subscribe(employ =>
{this.employes = employ})
}
}
app.component.html
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Salary</th>
<th scope="col">Age</th>
</tr>
</thead>
<tbody>
<tr *ngFor='let empo of employes ; let i = index '>
<th scope="row">{{i + 1}}</th>
<td>{{empo.employee_name}}</td>
<td>{{empo.employee_salary}}</td>
<td>{{empo.employee_age}}</td>
</tr>
</tbody>
</table>
答案 0 :(得分:0)
您的回复如下:
{ status: string, data: [], message: string }
所以您有两个选择:
在构造函数中
{this.employes = employ.data}
或
在模板视图中
<tr *ngFor='let empo of employes.data ; let i = index '>
如果API响应成功,其中之一必须有效
最好将http请求移到OnInit方法中, 因此您的组件应如下所示:
export class AppComponent implements OnInit {
employes;
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.http.get('http://dummy.restapiexample.com/api/v1/employees')
.subscribe(res => this.employes = res.data);
}
}