【问题标题】:Problem iterating through JSON in Angular在 Angular 中遍历 JSON 的问题
【发布时间】:2021-07-13 20:25:54
【问题描述】:

在我正在工作的 Angular 项目中,我正在尝试遍历位于我的项目中的一些 JSON。 Angular 项目可以编译,但我一直感到害怕:

错误错误:找不到不同的支持对象“[object Object]” “对象”类型。 NgFor 仅支持绑定到 Iterables,例如 数组。

据我了解,您不能迭代 JSON 对象 (???) - 您必须以某种方式将其转换为数组或一些“可迭代”容器/结构等才能获得 * 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}`);
  }
}

这是我的新雇员.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

【问题讨论】:

    标签: javascript angular typescript ngfor


    【解决方案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;
          });
        }
      }
      

      【讨论】:

      • 好的,所以“提取接口响应”应该在它自己的 .ts 文件中(?),它应该有导出而不是提取。尔格:“出口接口响应”。对吗?
      • 这似乎为我解决了问题。似乎关键是导出接口响应。它需要考虑状态字符串和被命名数据的员工数组。谢谢 Dawid Wekwejt。
      • @CuriousGeo66 是的,我希望将响应放在单独的文件中并将其导入 getEmployees 方法所在的位置。
      猜你喜欢
      • 2016-04-29
      • 1970-01-01
      • 2021-05-08
      • 2017-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      相关资源
      最近更新 更多