首页 > 解决方案 > 错误:找不到类型为“object”Angular 6 的不同支持对象“[object Object]”

问题描述

我有问题。我寻找其他解决方案,但没有找到对我有帮助的。

错误是:

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

我的模型.ts

export interface CEP {
    complemento: string;
    bairro: string;
    cidade: string;
    logradouro?: string;
    estado_info?: string[];
    cep: string;
    cidade_info?:string[]; 
    estado: string;
}

我的服务.ts

import { Injectable } from '@angular/core';
import { CEP } from './cep/cep.model';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
//import { map, tap } from 'rxjs/operators';

 @Injectable()
 export class CEPSerivce {

     constructor(private http: HttpClient) {}

     ceps(numCEP: string): Observable<CEP[]> {
         return this.http.get<CEP[]> 
      (`https://api.postmon.com.br/v1/cep/${numCEP}`);
     }
   }

我的模型.ts

 searchCEP() {

    console.log(this.cepDigitado);

    this.cepService.ceps(this.cepDigitado)
        .subscribe(cep => {
        this.cep = cep; console.log(this.cep); /*this.cepArray.push(this.cep);*/ console.log(this.cepArray);
        },
            error => { alert("Erro") });
}

我的组件.html

  <table>
    <tr *ngFor="let c of cep">
      <td>{{c.cidade}}</td>
    </tr>
  </table>

响应 JSON

{
   "complemento": "de 1907/1908 ao fim",
   "bairro": "Aeroporto",
   "cidade": "Barretos",
   "logradouro": "Rua 26",
   "estado_info": {
      "area_km2": "248.221,996",
      "codigo_ibge": "35",
      "nome": "São Paulo"
   },
  "cep": "14783232",
  "cidade_info": {
      "area_km2": "1566,161",
      "codigo_ibge": "3505500"
   },
   "estado": "SP"
}

标签: angularmultidimensional-arrayangularjs-directiveangular6

解决方案


*ngFor指令只对可迭代对象起作用。如果要遍历对象的所有属性,可以使用keyValue管道

<table>
    <tr *ngFor="let item of cep | keyValue">
      <td>{{item.key}} {{item.value}}</td>
    </tr>
</table>

注意:它需要 Angular 6.1 版本(keyValue管道在该版本中添加)


或者,如果您只想显示任何对象的单个属性,您可以考虑将cep结果放入ceps集合中,如下所示。然后现有的解决方案将按预期工作。

ceps: any[] = []
searchCEP() {
    console.log(this.cepDigitado);
    this.cepService.ceps(this.cepDigitado)
      .subscribe(cep => {
        this.ceps = [cep]; console.log(this.cep);
      })
}

推荐阅读