gpt4 book ai didi

javascript - 在 Angular 中遍历 JSON 的问题

转载 作者:行者123 更新时间:2023-12-04 07:23:18 25 4
gpt4 key购买 nike

在我正在工作的 Angular 项目中,我试图遍历位于我的项目中的一些 JSON。 Angular 项目可以编译,但我一直在担心:

ERROR Error: Cannot find a differ supporting object '[object Object]'of type 'object'. NgFor only supports binding to Iterables such asArrays.


据我了解,您不能迭代 JSON 对象 (???) - 您必须以某种方式将其转换为数组或一些“可迭代”容器/结构等,才能获得 * ngFor 去工作。我已经尝试了有关堆栈溢出的所有内容-我缺少将该对象更改为数组的位,因此我的 newemployee.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 的接口(interface):
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 不会返回一个数组而是一个对象,在您的组件上您应该这样做:

this.employeeService.getEmployees().subscribe((data) => {
this.emplist = data.data;
});
由于您的服务正在返回一个对象,因此您的 *ngFor 指令无法遍历它。

关于javascript - 在 Angular 中遍历 JSON 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68368920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com