javascript - 在 Angular 中遍历 JSON 的问题
在我正在进行的一个 Angular 项目中,我正尝试遍历位于我项目中的一些 JSON。Angular 项目可以编译,但我一直收到可怕的错误:
错误 错误:找不到支持类型为 'object' 的对象 '[object Object]' 的差异器。NgFor 仅支持绑定到可迭代的对象,例如数组。
据我所知,你不能直接迭代一个 JSON 对象 (???) —— 你必须以某种方式将它转换成一个数组或某种“可迭代”的容器/结构等,才能使 *ngFor 正常工作。我已经在 Stack Overflow 上几乎尝试了所有方法 —— 我缺少将该对象转换为数组的步骤,这样 mynewemployee.component.html 中的 *ngFor 才能正确工作:
<tr *ngFor="let employee of emplist">
这是我的服务 TypeScript 代码(employee.service.ts):
import { Injectable } from '@angular/core';
import { Employee2 } from '../employee2';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { MessageService } from '../message.service';
@Injectable({
providedIn: 'root',
})
export class EmployeeService {
url: string;
constructor(
private http: HttpClient,
private messageService: MessageService
) {
this.url = `/assets/json/employees.json`;
}
//gets the Employees from the file:
getEmployees(): Observable<Employee2[]> {
return this.http //.get(this.url)
.get<Employee2[]>(this.url)
.pipe(catchError(this.handleError<Employee2[]>('getEmployees', [])));
}
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.error(error); // log to console instead
this.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
private log(message: string) {
this.messageService.add(`EmployeeService: ${message}`);
}
}
这是我的 newemployee.component.ts:
import { Component, OnInit } from '@angular/core';
import { Employee2 } from '../employee2';
import { EmployeeService } from '../services/employee.service';
@Component({
selector: 'app-newemployee',
templateUrl: './newemployee.component.html',
styleUrls: ['./newemployee.component.css'],
})
export class NewemployeeComponent implements OnInit {
emplist: Employee2[];
// Inject the service into newemployees.component.ts file via a constructor.
constructor(private employeeService: EmployeeService) {}
ngOnInit(): void {
this.employeeService.getEmployees().subscribe((data) => {
this.emplist = data;
});
}
}
这是 newemployee.component.html:
<br>
<div class="col">
<h2>Department Store Employees</h2>
<table class="table table-bordered table-striped">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Salary</th>
<th scope="col">Age</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let employee of emplist">
<td scope="row">{{employee.id}}</td>
<td>{{employee.employee_name}} </td>
<td>{{employee.employee_salary}}</td>
<td>{{employee.employee_age}} </td>
</tr>
</tbody>
</table>
</div>
这也是 Employee2 的界面:
export interface Employee2{
id: number;
employee_name: string;
employee_salary: number;
employee_age: number;
profile_image: string; //path to image.
}
最终的 JSON 文件员工:
{
"status": "success",
"data": [{
"id": 1,
"employee_name": "John Public",
"employee_salary": 320800,
"employee_age": 61,
"profile_image": ""
}, {
"id": 2,
"employee_name": "John Summers",
"employee_salary": 170750,
"employee_age": 63,
"profile_image": ""
}, {
"id": 3,
"employee_name": "James Cox",
"employee_salary": 86000,
"employee_age": 66,
"profile_image": ""
},{
"id": 24,
"employee_name": "Chuck Wilder",
"employee_salary": 85600,
"employee_age": 23,
"profile_image": ""
}],
"message": "Successfully! All records has been fetched."
}
理想情况下,这应该是它的样子
答案#1
你从服务中获取的 JSON 不是返回一个数组,而是一个对象,在你的组件中你应该这样做:
this.employeeService.getEmployees().subscribe((data) => {
this.emplist = data.data;
});
由于你的服务返回的是一个对象,你的 *ngFor 指令无法对它进行迭代。
答案#2
尝试这些更改。问题是你正在将 JSON 转换为与原结构不同的类型。
extract interface Response {
status: string;
data: Employee2[];
}
getEmployees(): Observable<Response> {
return this.http //.get(this.url)
.get<Response>(this.url)
.pipe(catchError(this.handleError<Response>('getEmployees', {})));
}
export class NewemployeeComponent implements OnInit {
emplist: Employee2[];
// Inject the service into newemployees.component.ts file via a constructor.
constructor(private employeeService: EmployeeService) {}
ngOnInit(): void {
this.employeeService.getEmployees().subscribe((response) => {
this.emplist = response.data;
});
}
}
