I have a problem with. I looked for other solutions and found none that would help me.
The error is:
ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
My model.ts
export interface CEP {
complemento: string;
bairro: string;
cidade: string;
logradouro?: string;
estado_info?: string[];
cep: string;
cidade_info?:string[];
estado: string;
}
My service.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}`);
}
}
My model.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") });
}
My component.html
<table>
<tr *ngFor="let c of cep">
<td>{{c.cidade}}</td>
</tr>
</table>
Response 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 directive do work on only iterable object. If you want to loop over all the property of an object, you could use keyValue pipe
<table>
<tr *ngFor="let item of cep | keyValue">
<td>{{item.key}} {{item.value}}</td>
</tr>
</table>
Note: it needs Angular 6.1 version (keyValue pipe got add in that release)
Or if you just wanted to show up just a single property of any object, you can consider putting cep result into ceps collection like below. Then existing solution would work as expected.
ceps: any[] = []
searchCEP() {
console.log(this.cepDigitado);
this.cepService.ceps(this.cepDigitado)
.subscribe(cep => {
this.ceps = [cep]; console.log(this.cep);
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With