错误:NG0900:尝试比较"[对象对象]"时出错。只允许数组和可迭代对象



Im目前正在开发crud应用程序的前端部分。当我得到这个错误时,我正在实现延迟分页

错误:NG0900:尝试区分"[对象对象]"时出错。只允许使用数组和可迭代项

我已经研究了很多有同样错误的问题,但我没有找到任何解决方案

Obs:已经尝试使用管道| keyvalue,无法使用

这是我传递给分页的对象的一部分=cidades:

[
{
"id": 6,
"nome": "Florianópolis",
"qtdHabitantes": null,
"estado": "SC"
},
...
]

这是我请求的服务

import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { Pageable } from '../pageable';
import { RequestUtil } from '../request-util';
import { Cidade } from './cidade';
import { CidadeFiltro } from './cidadeFiltro';
@Injectable({
providedIn: 'root'
})
export class CidadeService {
apiUrl = environment.apiUrl;
cidadesUrl = environment.slashApi + '/cidades';
constructor(private http: HttpClient) { }
listar(filtro: CidadeFiltro, pageable: Pageable): Observable<any>{
const options = RequestUtil.buildOptions(Object.assign(filtro, pageable));
return this.http.get<any>(`${this.cidadesUrl}`, options);
}
...

我的组件.ts:

export class CidadesComponent implements OnInit, OnChanges {
@ViewChild('grid') grid: any;
cidades: any[] = [];
estado = new Estado();
estados = [];
estadoSelected:any = '';
filtro = new CidadeFiltro();
pageable = new Pageable();
totalRegistros = 0;
@BlockUI('lista-cidades') blockUI!: NgBlockUI;
constructor(private cidadeService:CidadeService, private messageService: MessageService ) { }
ngOnChanges(changes: SimpleChanges): void {
this.cidades = this.cidades
}
ngOnInit() {
this.listar();
this.estados = this.estado.estados;
}
listar(pagina:number = 0){
this.blockUI.start();
this.filtro.estado = this.estadoSelected.name;
this.pageable.page = pagina;
this.cidadeService.listar(this.filtro, this.pageable).pipe(finalize(() => this.blockUI.stop())).subscribe(data => {
this.totalRegistros = data.totalElements;
this.cidades = data.content;
}),
retry(3),
catchError(error => {
console.log('Não foi possível listar as cidades');
return of(0);
});
}

最后是我的组件.html

<div *blockUI="'lista-cidades'">
<p-table [value]="cidades" #grid
[lazy]="true" [totalRecords]="registros" (onLazyLoad)="aoMudarPagina($event)"
[paginator]="true" [rows]="size" responsiveLayout="scroll">
<ng-template pTemplate="emptymessage">
<tr><td>Nenhuma cidade encontrada</td></tr>
</ng-template>
<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 class="acoes">
<button pButton icon="pi pi-pencil" pTooltip="Editar" tooltipPosition="top" [routerLink]="['/cidades', cidade.id]"></button>
<button pButton class="p-button-danger" icon="pi pi-trash"  pTooltip="Excluir" tooltipPosition="top"
(click)="deletar(cidade)"></button>
</td>
</tr>
</ng-template>
</p-table>
</div>

错误日志:

ERROR Error: NG0900: Error trying to diff '[object Object]'. Only arrays and iterables are allowed
at DefaultIterableDiffer.diff (core.mjs:27502)
at NgForOf.ngDoCheck (common.mjs:3170)
at callHook (core.mjs:2552)
at callHooks (core.mjs:2511)
at executeCheckHooks (core.mjs:2443)
at refreshView (core.mjs:9493)
at refreshEmbeddedViews (core.mjs:10609)
at refreshView (core.mjs:9508)
at refreshComponent (core.mjs:10655)
at refreshChildComponents (core.mjs:9280)

有人能帮我吗?

UPDATE我考虑过用listar()方法实现这段代码:

listar(pagina:number = 0){
this.blockUI.start();
this.filtro.estado = this.estadoSelected.name;
this.pageable.page = pagina;
this.cidadeService.listar(this.filtro, this.pageable).pipe(finalize(() => this.blockUI.stop())).subscribe(data => {
this.totalRegistros = data.totalElements;
this.cidades.push(data.content);
this.cidades = this.cidades[0];
console.log(this.cidades)
})

但后来我得到错误

错误类型错误:无法读取未定义(读取"推送"(的属性

我的列表变成空

我突然想到的一件事是,您使用的是any类型。

在服务中执行类似于return this的操作。http.get<Cidades[]>将确保响应将被解析为Cidades数组,并可能让您知道那里是否出现了问题。(我记不清它是否会投球,如果不会的话(

查看请求键入的响应

另外,使用cidades: Cidades[] = [];,当分配了其他内容时,您可能会看到问题所在。

尽可能避免使用类型any,否则你会失去所有类型的安全性,可能会发生奇怪的事情。

例如,如果不是Cidades[]的其他东西被分配给这个.Cidades,编译器会在设计时抱怨,你可以看到发生了什么。

由于我没有用你的代码创建一个项目,我不知道确切的错误是什么。

当我遇到这个问题时,我的代码是这样的:

public join: IReservation[] |any; 
loadreserve(): void {
this.reserve.list().subscribe((daya) => {
this.dispo = daya; 
for (let ter of this.dispo) {
let toto : number|any = ter.terrain?.nbrJoueurs; 
let tat: number|any = ter.nbrjoueur; 
this.comp = toto - tat;
if (this.comp >= this.numberofJoin) {
this.join = ter;
console.log(this.join);
}
}
});
}

问题:在我的for循环中,我返回了一个对象来显示它,但我需要一个对象数组,所以我做了这个修改:

loadreserve(): void {
this.join = [];
this.reserve.list().subscribe((daya) => {
this.dispo = daya; 
for (let ter of this.dispo) {
let toto : number|any = ter.terrain?.nbrJoueurs; 
let tat: number|any = ter.nbrjoueur; 
this.comp = toto - tat;
if (this.comp >= this.numberofJoin) {
this.join.push(ter);
console.log(this.join);
}
}
});
}

它对我有效。

我有一个带有Angular前端的.Net Core API。我的问题是由于调用外部API导致的,该API返回HTTP 500内部服务器错误。未处理的错误随后在控制台中显示为NG0900。最终的根本原因是数据迁移未应用于外部API。

最新更新