Home  >  Q&A  >  body text

Error NG0900 An error occurred while trying to compare. Only arrays and iterable objects allowed

Using *ngFor I am able to render the data but it throws this error

Error Error: NG0900: An error occurred while trying to compare '[object Object]'. Only arrays and iterable objects allowed

This is my service method

async getEditions(): Promise<Observable<Cigales>> {
    return this.http.get<Cigales>(url+"/candidates/editions", httpOptions).pipe(
      tap((getEditions: Cigales) => this.log('getEditions' + getEditions)),
      catchError(this.handleError<Cigales>('getEditions'))
    );
  }

This is my component method

editions: Cigale[] = [];

  async getEditions(): Promise<void> {
    await this.CigalesService.getEditions().then(res=> {
      res.subscribe(data => {
        this.editions = [];
        this.editions = data.content;
      })
    })
  }

This is my Cigales interface

export interface Cigales {
  content: Array<Cigale>,
  pageable: pageable,
  last: string;
  totalPages: string;
  totalElements: string;
  size: string;
  number: string;
  sort: sort;
  first: string;
  numberOfElements: string;
  empty: string;
}

export interface Cigale {
  id?: string;
  eventName: string;
  eventStartDate: string;
  eventEndDate: string;
}

type sort = {
  empty: boolean,
  sorted: boolean,
  unsorted: boolean
}

type pageable = {
  sort: sort,
  offset: string;
  pageNumber: string;
  pageSize: string;
  paged: string;
  unpaged: string;
}

This is my component.html

<tr *ngFor="let item of editions">
        <td>{{item.eventName}}</td>
        <td>{{item.eventStartDate}}</td>
        <td>{{item.eventEndDate}}</td>
        <td>
          <a class="d-inline" role="button" data-bs-toggle="modal" data-bs-target="#application-modal"><i class="bi bi-clipboard"></i></a>
          <a class="d-inline" role="button" data-bs-toggle="modal" data-bs-target="#application-modal"><i class="bi bi-pencil-square"></i></a>
        </td>
      </tr>

Console.log(this.editions) and I get an array of two objects

Console results

EDIT: I tried Array.isArray(this.editions) and it returns true

P粉226667290P粉226667290237 days ago406

reply all(1)I'll reply

  • P粉852578075

    P粉8525780752024-02-26 14:43:53

    First of all, the error you are facing is related to you trying to use an object instead of an array as the data source for the *ngFor directive.

    Secondly, try assigning data to this.editions, for example:

    async getEditions(): Promise {
      await this.CigalesService.getEditions().then(res=> {
        res.subscribe(data => {
          this.editions= [...data.content];
        })
      })
    }

    Additionally, I recommend that you avoid using Promises in Angular applications and instead make your code more reactive by leveraging subscriptions.

    reply
    0
  • Cancelreply