angular - 错误:找不到类型为“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"
}
解决方案
*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);
})
}
推荐阅读
- stm32 - STM32F373 SDADC Hal - 为什么在单端零参考模式下对 HAL_SDADC_Start_DMA 中的 pData 使用 uint32_t 类型?
- python - Pyside2构建几个按钮和内存
- regex - 仅用感叹号提取字母和连字符问题
- sqlite - 一个语句中的两个查询
- xcode - 使用键盘在 Xcode 中的不同区域之间导航
- python - Python3 - CSV 编写器
- javascript - 仅数据列表验证选项
- python - While 循环无法处理值 10
- c++ - 在 Windows 上构建一个简单的 C++ 项目,使用 CMake 和 clang
- c# - 查看asp.net mvc和asp.net core mvc的目录编译时间差