I have already looked into many questions like this but none of them could help me out. I'm receiving a obj that returns a list of cities with their names, habitants and states. Here's my http service request:
cidadesUrl = 'http://localhost:8080/api/cidades';
constructor(private http: HttpClient) { }
listar(): Observable<Cidade[]>{
return this.http.get<Cidade[]>(this.cidadesUrl);
}
and here's the calling to the service:
cidades!: Cidade[];
constructor(private cidadeService:CidadeService) { }
listar(){
this.cidadeService.listar().subscribe(data => { this.cidades = data });
console.log(this.cidades);
}
and my html:
<p-table [paginator]="true" [rows]="4" responsiveLayout="scroll">
<ng-template pTemplate="header">
<tr>
<th>Nome</th>
<th>Habitantes</th>
<th>Estado</th>
<th>Ações</th>
</tr>
</ng-template>
<ng-template pTemplate="body" *ngFor="let cidade of tabela">
<tr>
<td>{{cidade.nome}}</td>
<td>{{cidade.qtdHabitantes | number}}</td>
<td>{{cidade.estado}}</td>
<td >
<button pButton icon="pi pi-pencil" pTooltip="Editar" tooltipPosition="top"></button>
<button pButton icon="pi pi-trash" pTooltip="Excluir" tooltipPosition="top"></button>
</td>
</tr>
</ng-template>
</p-table>
Tabela variable:
@Input() tabela!: Cidade[];
I don't know why but when the page loads, i get the error:
ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
When I open the Network tab in console, the cities are there, but they dont show up in the table
Hoping that i could find a answer to this
CodePudding user response:
You p-table code is wrong it should be :-
<p-table [value]="tabela" [paginator]="true" [rows]="4" responsiveLayout="scroll">
<ng-template pTemplate="header">
<tr>
<th>Nome</th>
<th>Habitantes</th>
<th>Estado</th>
<th>Ações</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-cidade>
<tr>
<td>{{cidade.nome}}</td>
<td>{{cidade.qtdHabitantes | number}}</td>
<td>{{cidade.estado}}</td>
<td >
<button pButton icon="pi pi-pencil" pTooltip="Editar" tooltipPosition="top"></button>
<button pButton icon="pi pi-trash" pTooltip="Excluir" tooltipPosition="top"></button>
</td>
</tr>
</ng-template>
</p-table>