从 *ngFor 迭代对象数组 - Angular

Iterate an array of Objects from *ngFor - Angular

我的版本是13.0.4

我只是想用 ngFor 从 component.html 开始迭代,但它没有显示,而且它使页面出现错误。 html:

<select>
    <option *ngFor="let region of regiones" value="{{ region.numero }}"> {{ region.nombre }} </option>
</select>

我的界面:

export interface Region {
    nombre: String,
    numero: number
}

我正在获取服务中的区域 (regiones.service.ts)

import { Injectable } from '@angular/core';
import { Region } from '../interfaces/regiones.interface';
import { HttpClient } from '@angular/common/http';


@Injectable({
  providedIn: 'root'
})
export class RegionesService {

  constructor(private _http: HttpClient) { }

  private _regiones: Region[] = [
      { nombre: 'Región Metropolitana de Santiago', numero: 0 },
      { nombre: 'Región de Arica y Parinacota', numero: 15 },
      { nombre: 'Región de Tarapacá', numero: 1 },
      { nombre: 'Región de Antofagasta', numero: 2 },
      { nombre: 'Región de Atacama', numero: 3 },
      { nombre: 'Región de Coquimbo', numero: 4 },
      { nombre: 'Región de Valparaíso', numero: 5 },
      { nombre: 'Región del Libertador General Bernardo O’Higgins.', numero: 6 },
      { nombre: 'Región del Maule', numero: 7 },
      { nombre: 'Región del Ñuble', numero: 16 },
      { nombre: 'Región del Biobío', numero: 8 },
      { nombre: 'Región de La Araucanía', numero: 9 },
      { nombre: 'Región de Los Ríos', numero: 14 },
      { nombre: 'Región de Los Lagos', numero: 10 },
      { nombre: 'Región de Aysén del General Carlos Ibáñez del Campo', numero: 11 },
      { nombre: 'Región de Magallanes y la Antártica Chilena', numero: 12 },
  ]
  

  getRegiones() { 
    return { ...this._regiones };
  }

}

然后我从组件中获取它们:(inicio.component.ts)

export class InicioComponent implements OnInit {

  constructor(private regionesService: RegionesService) { }
  regiones: Region[] = this.regionesService.getRegiones()

  ngOnInit(): void {
    console.log(this.regiones);    
  }

}

这是我在控制台中得到的:

console log image

结果:

result

错误:

core.mjs:6469 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
    at NgForOf.ngDoCheck (common.mjs:3156:27)
    at callHook (core.mjs:2536:1)
    at callHooks (core.mjs:2495:1)
    at executeInitAndCheckHooks (core.mjs:2446:1)
    at refreshView (core.mjs:9484:1)
    at refreshComponent (core.mjs:10640:1)
    at refreshChildComponents (core.mjs:9265:1)
    at refreshView (core.mjs:9519:1)
    at refreshEmbeddedViews (core.mjs:10594:1)
    at refreshView (core.mjs:9493:1)

问题出在您的 getRegiones() 函数上:

return { ...this._regiones };

此函数的 return 值是对象 - 不是数组。这就是为什么 Angular 抱怨无法通过它循环。

您可以使用 *ngFor="let region of Object.values(regiones)" 将其转换回数组或更改 getRegiones() 函数的结果。