错误:NG0900:尝试比较“[object Object]”时出错。仅允许数组和可迭代对象

问题描述 投票:0回答:4

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

错误:NG0900:尝试比较“[object Object]”时出错。仅允许数组和可迭代对象

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

观察:已经尝试使用管道

| 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);
    });
  }

最后是我的component.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)

有人可以帮助我吗?

更新 我考虑过在

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)
    })

但后来我收到错误

错误类型错误:无法读取未定义的属性(读取“push”)

我的列表变空了

angular typescript primeng
4个回答
4
投票

我突然想到的一件事是你正在使用 any 类型。

在服务中执行诸如 return this.http.get 之类的操作将确保响应将被解析为 Cidades 数组,并且可能会让您知道那里是否出现问题。 (如果不能的话我记不太清了是否抛出)

查看请求输入回复

另外,使用

cidades: Cidades[] = [];
代替,当分配了其他内容时,您可能会看到问题出在哪里。

尽可能避免使用类型

any
,否则你将失去所有类型安全性,并且可能会发生奇怪的事情。

例如,如果将不是 Cidades[] 的其他内容分配给 this.cidades,编译器会在设计时发出警告,您可以看到发生了什么。

由于我没有使用您的代码创建项目,所以我不知道错误到底是什么。


0
投票

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

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);
            }
        }
    });
}

它对我有用。


0
投票

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


0
投票

我的问题是我的 API 返回了一个包含数组的对象:

  {
  "$id": "1",
  "$values": [
    {
      "$id": "2",
      "id": 5,
      "name": "stringskdlasdkjsjdkasjdljsakdljsad",
      "imageUrl": "skajddjkasdkjldajkdajkadsjkdsaj",
      "description": "stringsdasdksadlskda;lsdksaldka;sldkas;ldkasl;dk;sldkal;dkas;ldkals;kd;asld",
      "creationDate": "2024-04-19T14:55:48.415",
      "writtenBy": "string",
      "content": "string",
      "commentsCount": 0,
      "comments": null,
      "likesAmount": 0,
      "creationDateFormatted": null
    },

在这种情况下,我需要调整观察者以提取值:

   this.blogsObserver = {
      next:(response) => {
        // @ts-ignore
        this.blogsArray= response["$values"]
      },
      error:(error) => {
        console.error('Error loading blogs',error)
      },
      complete:() => {
        console.log('Loaded blogs from the API.')
      }
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.