Issue: NG0900: Encountered an error while attempting to differentiate '[object Object]'. Only arrays and iterables are permitted

I'm currently working on the frontend development of a crud application. While implementing lazy pagination, I encountered an error

Error: NG0900: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

I have searched through numerous questions with the same error, but none provided a solution

Note: I attempted using the pipe | keyvalue, but it did not work

Here is a snippet of the object being passed to the pagination = cities:

[
    {
        "id": 6,
        "name": "Florianópolis",
        "population": null,
        "state": "SC"
    },
    ...
]

Below is the service where the request is made:

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 { City } from './city';
import { CityFilter } from './cityFilter';

@Injectable({
  providedIn: 'root'
})
export class CityService {

  apiUrl = environment.apiUrl;
  citiesUrl = environment.slashApi + '/cities';

  constructor(private http: HttpClient) { }

  list(filter: CityFilter, pageable: Pageable): Observable<any>{
    const options = RequestUtil.buildOptions(Object.assign(filter, pageable));
    return this.http.get<any>(`${this.citiesUrl}`, options);
  }
  ...

My component.ts:

export class CitiesComponent implements OnInit, OnChanges {

  @ViewChild('grid') grid: any;

  cities: any[] = [];

  state = new State();

  states = [];

  selectedState:any = '';

  filter = new CityFilter();
  pageable = new Pageable();

  totalRecords = 0;

  @BlockUI('list-cities') blockUI!: NgBlockUI;

  constructor(private cityService:CityService, private messageService: MessageService ) { }

  ngOnChanges(changes: SimpleChanges): void {
    this.cities = this.cities
  }

  ngOnInit() {
    this.list();
    this.states = this.state.states;
  }

  list(page:number = 0){
    this.blockUI.start();
    this.filter.state = this.selectedState.name;
    this.pageable.page = page;
    this.cityService.list(this.filter, this.pageable).pipe(finalize(() => this.blockUI.stop())).subscribe(data => {
      this.totalRecords = data.totalElements;
      this.cities = data.content;
    }),
    retry(3),
    catchError(error => {
      console.log('Could not retrieve the cities');
      return of(0);
    });
  }

And lastly, my component.html

<div *blockUI="'list-cities'">
  <p-table [value]="cities" #grid
    [lazy]="true" [totalRecords]="records" (onLazyLoad)="onPageChange($event)"
  [paginator]="true" [rows]="size" responsiveLayout="scroll">

    <ng-template pTemplate="emptymessage">
      <tr><td>No cities found</td></tr>
    </ng-template>

    <ng-template pTemplate="header">
        <tr>
            <th>Name</th>
            <th>Population</th>
            <th>State</th>
            <th>Actions</th>
        </tr>
    </ng-template>

    <ng-template pTemplate="body" let-city>
        <tr>
            <td>{{city.name}}</td>
            <td>{{city.population | number}}</td>
            <td>{{city.state}}</td>
            <td class="actions">
              <button pButton icon="pi pi-pencil" pTooltip="Edit" tooltipPosition="top" [routerLink]="['/cities', city.id]"></button>
              <button pButton class="p-button-danger" icon="pi pi-trash"  pTooltip="Delete" tooltipPosition="top"
              (click)="delete(city)"></button>
            </td>
        </tr>
    </ng-template>
  </p-table>
</div>

error log:

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)

Can someone provide some guidance?

UPDATE I am considering implementing this code in the list() method:

list(page:number = 0){
    this.blockUI.start();
    this.filter.state = this.selectedState.name;
    this.pageable.page = page;
    this.cityService.list(this.filter, this.pageable).pipe(finalize(() => this.blockUI.stop())).subscribe(data => {
      this.totalRecords = data.totalElements;
      this.cities.push(data.content);
      this.cities = this.cities[0];
      console.log(this.cities)
    })

but then i get the error

ERROR TypeError: Cannot read properties of undefined (reading 'push')

And my list becomes empty

Answer №1

It seems like you are using the `any` type, which may lead to potential issues.

Consider returning `this.http.get` in the service to ensure that the response is parsed correctly and to catch any errors early on. You can refer to Requesting a typed response for more information.

Instead of using `cidades: Cidades[] = [];`, try using explicit typing to better track the data types and detect any discrepancies when assigning values.

Avoid relying too heavily on the `any` type as it can compromise type safety and introduce unexpected behaviors.

If an incorrect value is assigned to `this.cidades`, the compiler will provide warnings during design time to help identify the issue.

Without seeing your full code, it's difficult to pinpoint the exact error you may be encountering.

Answer №2

When I encountered the issue, my code looked like this:

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

The issue arose when I realized that I needed an array of objects instead of just one object in my loop. To resolve this problem, I made the following modification:

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

This adjustment resolved my issue and now the code works correctly.

Answer №3

Running a .Net Core API alongside an Angular frontend posed a challenge for me. The problem emerged when I attempted to access an external API, only to receive a frustrating HTTP 500 Server Error in return. This error manifested as NG0900 on the console due to lack of proper handling. After much investigation, it was discovered that the root cause stemmed from the fact that the necessary data migrations had not been implemented on the external API.

Answer №4

One issue I encountered was when my API sent back an object containing an array:

  {
  "$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
    },

To handle this situation, I had to update my observer to extract the necessary values:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to prevent resizing of an Angular 2 Material md-textarea component?

Having trouble disabling the resizing option on an md-textarea. Here is the method I've attempted: <md-textarea md-no-resize rows="3"></md-textarea> Any suggestions on how to make it work? ...

In the world of mathematics, the equation 1+1 may actually equal 11 instead

I have a TypeScript class where there are no import statements at the top. The issue I am facing is that when I use calculateDate() and run the addMonth(new Date(), 1) function, it ends up adding 11 months to today instead of just 2. Upon investigation, ...

Configuring Spring Boot with Security to enable secure communication with an Angular web application

I currently have a spring boot application running on domain A. Its main purpose is to expose REST endpoints. In addition, I have an angular 8 application that can be deployed either on the same domain A or on another domain B. The spring boot app is able ...

Tips for utilizing Optical Character Recognition in Node.js with a buffer image:

Are you facing difficulties in creating an API that extracts data from an image without saving it on the server? Look no further, as I have a solution for you. When testing with the URL '', everything works perfectly. However, using a buffer or l ...

An error is encountered when attempting to retrieve the list using axios

For this project, I am required to fetch a list from the following resource: http://jsonplaceholder.typicode.com/photos The controller setup is as follows: @JsonController('/photo') @Service() export class PhotoController { const ...

The customization of primary and secondary palettes in React MUI5 with TypeScript theme is restricted and cannot

Our design team put together numerous custom palettes and additional properties. While this posed no problem in JS, transitioning to TS has proven to be quite challenging. I managed to prevent any errors from being thrown in the createTheme file, but using ...

In TypeScript with React, utilizing ref to access the video element and trigger the .play() method

I have a TypeScript React video component that I want to play when clicked. My approach is to use a click handler that accesses the video through a ref and calls .play(), but I keep encountering this error: TS2339: Property 'play' does not exist ...

STOMP connection to RabbitMQ from browser is not allowed

My RabbitMQ Docker container has the Stomp plugin enabled, but I am encountering connection issues. Each time I try to establish a connection, I receive this error message: The STOMP connection from 172.19.0.1:54578 to 172.19.0.2:61613 was terminated with ...

Modify visibility within a subclass

Is there a way to modify property visibility in a child class from protected to public? Consider the following code snippet: class BaseFoo { protected foo; } class Foo extends BaseFoo { foo = 1; } new Foo().foo; It seems that this change is pos ...

A React component written in Typescript that can handle onChange events for both TextAreas and Input fields

I'm a beginner in typescript and am working on creating an input component. When the component receives type="text", it renders an input. Similarly, when it receives type="textarea", it renders a textarea. However, I am facing an issue with typescript ...

Having trouble getting ng-bootstrap to function properly in Angular 4?

After recently familiarizing myself with Angular 4, I decided to integrate bootstrap into my project. Following the instructions provided on the ng-bootstrap website (), I installed ng-bootstrap as recommended. Despite following all the steps outlined on ...

Issue encountered in TypeScript: Property 'counter' is not found in the specified type '{}'.ts

Hey there, I'm currently facing an issue while trying to convert a working JavaScript example to TypeScript (tsx). The error message I keep encountering is: Property 'counter' does not exist on type '{}'.ts at several locations wh ...

TS: Deduce explicit typing through method chaining

After overcoming all obstacles, I am finally ready to unleash the first version of my form validation library. Below is a snippet of the code (simplified for clarity) interface Validation { name: string message: string params?: Record<string, any ...

What is the best way to transfer the useState set state function to a child component in TypeScript?

Since delving into typescript, I've encountered an issue with passing a useState setter function. My parent component looks like this: const [word, setword] = useState('run') When passing props to the child component, it's done as fol ...

Creating new routes and lazy-loading in Angular CLI page generator

I have questions regarding the process of page generation and route creation by the CLI. When a new page is generated using the ng CLI, it creates the page module, HTML, spec, and SCSS files, as well as updates the routing module. 1) By default, the page ...

If two requests are made at the same time, they will both yield identical results

Encountering an issue where running two separate HttpClient requests to my Spring Boot backend yields the same result for both requests (the first request's result). This occurs approximately 30% of the time: //request 1 with url_1= "http://local ...

Step-by-step guide on building a mat-table with nested attributes as individual rows

Here is the data structure I am working with: const families = [ { name: "Alice", children: [ { name: "Sophia" }, { name: "Liam" ...

Utilize ViewChild to handle changing elements in Angular 2 and Ionic 2 applications

I am facing an issue where I want to dynamically add multiple IonicSlides, but I am unable to use @viewChild. Can anyone suggest a solution for this problem? Template.html : <div *ngFor="let name of title;let i = index;"> <ion-slide ...

Is it feasible to develop a TypeScript module in npm that serves as a dual-purpose tool, functioning as both a command line utility

My goal is to develop an npm TypeScript module that serves dual purposes - acting as a command line utility and exporting methods for use in other modules. The issue arises when the module intended for use as a command line utility requires a node shebang ...

Displaying various versions of Angular I'm sorry, but

I recently upgraded my ASP.Net Angular 4 project to the latest version of Angular. To achieve this, I used the following commands: npm install -g npm-check-updates ncu -u After updating, I reopened my project and checked the packages.json file to confirm ...