在 Angular 中遍历 JSON 时出现问题
Problem iterating through JSON in Angular
在我工作的 Angular 项目中,我试图遍历位于我的项目中的一些 JSON。 Angular 项目编译,但我一直感到害怕:
ERROR Error: Cannot find a differ supporting object '[object Object]'
of type 'object'. NgFor only supports binding to Iterables such as
Arrays.
据我了解,您不能迭代 JSON (???) 的对象——您必须以某种方式将其转换为数组或某些“可迭代”container/structure 等为了让 *ngFor 工作。我已经尝试了有关堆栈溢出的所有内容——我缺少将该对象更改为数组的位,因此我的 newemployee.component.html 中的 *ngFor 可以正常工作:
<tr *ngFor="let employee of emplist">
这是我的服务打字稿代码 (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."
}
Ideally this is what it should look like
您从服务中检索的 JSON 不是 return 数组而是一个对象,在您的组件上您应该这样做:
this.employeeService.getEmployees().subscribe((data) => {
this.emplist = data.data;
});
由于您的服务正在 returning 一个对象,您的 *ngFor 指令无法遍历它。
尝试进行此更改。问题是您正在将 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;
});
}
}
在我工作的 Angular 项目中,我试图遍历位于我的项目中的一些 JSON。 Angular 项目编译,但我一直感到害怕:
ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
据我了解,您不能迭代 JSON (???) 的对象——您必须以某种方式将其转换为数组或某些“可迭代”container/structure 等为了让 *ngFor 工作。我已经尝试了有关堆栈溢出的所有内容——我缺少将该对象更改为数组的位,因此我的 newemployee.component.html 中的 *ngFor 可以正常工作:
<tr *ngFor="let employee of emplist">
这是我的服务打字稿代码 (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."
}
Ideally this is what it should look like
您从服务中检索的 JSON 不是 return 数组而是一个对象,在您的组件上您应该这样做:
this.employeeService.getEmployees().subscribe((data) => {
this.emplist = data.data;
});
由于您的服务正在 returning 一个对象,您的 *ngFor 指令无法遍历它。
尝试进行此更改。问题是您正在将 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;
});
}
}