The Angular framework is unable to locate a differ that supports the object '[object Object]' which is of type 'object'

In my Angular project, I am calling an API and receiving the following JSON data:

 {
        "id": 16,
        "poste": "ameur taboui",
        "desciption": "f",
        "service": "f",
        "creationDate": "2022-10-13",
        "updatedDate": "2022-10-24",
        "active": true,
        "personnelPosteListe": {
            "id": 1,
            "nomPersonnel": "ADMIN",
            "prenomPersonnel": "ADMIN",
            "matricule": 2564,
            "dateNaissance": "2022-07-26",
            "cin": 7858585,
            "telephone": 2554884,
            "adresse": "tunis",
            "dateAff": "2022-07-26",
            "dateFinAff": "2022-07-26",
            "typeContrat": "test",
            "champInterim": "f",
            "active": true
        },
       
    },

When trying to access personnelPosteListe in my HTML, I encountered the following error:

Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays. Any help on this? Here is my TS file:

onGetPosteListeByID() {
    this.grhService
      .getPosteListeById(this.id)
      .pipe(takeUntil(this.onDestroy$))
      .subscribe(
        (data) => {
          this.poste = data;
          console.log(this.poste);
        },
        (err) => {
          console.log(err);
        }
      );
  }
}

This is my HTML :

<table class="table table-striped table-hover  table-bordered text-center table-centre table-res">
                    <thead class="thead-light">
                        <tr>
                            <th> {{"Nom" | translate }} </th>
                            <th> {{"Prénom" | translate }}</th>
                            <th> {{"Type de contrat" | translate}}</th>
                            <th> {{"Matricule" | translate }}</th>
                            <th> {{"Telephone" | translate }}</th>

                        </tr>
                        <tr *ngFor="let b of poste?.personnelPosteListe ; trackBy: trackByMethod ">
                            <td> {{ b?.nomPersonnel}}</td>
                            <td> {{ b?.prenomPersonnel }}</td>
                            .
                            .
                            .
                            .
                        </tr>

                    </thead>
    </table>

Answer №1

The error is occurring because the poste?.personnelPosteListe in the JSON data is an object, whereas ngFor directive can only iterate over arrays. To resolve this issue, you may need to convert this list into an array either on the client side or server side.

Answer №2

This issue arises because the personnelPosteListe is being treated as an object when ngFor expects an array.

It could be a server-side problem where you are receiving an object instead of an array, especially if personnelPosteListe only has one item. Some APIs may behave in this manner. One solution is to manually convert it to an array on the client side:

onGetPosteListeByID() {
    this.grhService.getPosteListeById(this.id).pipe(
      map(data => {
        if(Array.isArray(data.personnelPosteListe)) return data;
        return { ...data, personnelPosteListe: [data.personnelPosteListe]};
      }),
      takeUntil(this.onDestroy$),
    ).subscribe(
        (data) => {
          this.poste = data;
          console.log(this.poste);
        },
        (err) => {
          console.log(err);
        }
      );
  }
}

Answer №3

After carefully reviewing your article, I would recommend utilizing the KeyValuePipe to extract 'nomPersonnel' and 'prenomPersonnel'

<div *ngFor="let item of object | keyvalue">
  {{item.key}}:{{item.value}}
</div>

Additionally, you may find some valuable insights in this post for alternative solutions.

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

The return type in Typescript is populated with a generic type name that lacks meaningful

When utilizing ts-results-es, I encounter an issue. This library aids in wrapping errors within a class to provide insight into potential function errors. Here is a simplified class definition: interface BaseResult<T, E> {} class Err<E> imple ...

Mapping an array of strings to model field values in EXTJS

I currently work with EXT JS 4.1.1. Upon receiving a JSON response structured as follows: { values: ["A","B","C"] } I proceed to define a model in the following manner: Ext4.define('model', { extends: 'Ext4.data.model', fiel ...

"Comparing the use of single Angular libraries versus multiple libraries on npm

I am considering consolidating all my libraries (57 in total) into a single folder called @my-organisation/team. This is because each library has many dependencies on one another and managing versioning & dependencies separately would be difficult. After s ...

App not displaying iOS push notifications

Trying to implement push notifications in my iOS7 app but encountering issues. The push notification does not appear. I have followed the process of creating certificates and provisioning profiles. Currently, it is only built for development, with plans t ...

Creating a hierarchical JSON format for a nested commenting system

I have a JSON data representing a multi-level comment system as shown below: [{ "thread_id": 2710, "parent_id": "", "username": "string", "comment": "string", "postdate": "2017-06-09T07:12:32.000Z", "id": 1 }, { "thread_id": 2710, "parent_ ...

A step-by-step guide on integrating a proxy into a Node/Express website

I have a website running on Node with the Express framework. My objective is to collect data from the Yahoo Placefinder API, which does not support JSONP. Therefore, I need to send my JQuery.getJSON request to a proxy. This proxy will then generate an HTT ...

Persist JSON data in [CLLocation] using SWIFT

My script retrieves nearby locations based on a specific location. I successfully extracted the coordinates of all nearby places and here is how the JSON data appears: UPDATED JSON This is the structure of the JSON: { "results" : [ { "id" : ...

Appending a new element to a JSON object using JavaScript

Hey there, I have a JSON object called departments. When I use console.log(departments) it displays the following data: { _id: 58089a9c86337d1894ae1834, departmentName: 'Software Engineering', clientId: '57ff553e94542e1c2fd41d26', ...

Although the cucumber tests indicate success, protractor fails to interact with the elements on the webpage

Recently, I delved into the realm of Protractor+Cucumber+Typescript and devised a sample framework utilizing Page Object Design along with a small script to execute some click actions. URL: My endeavor to click on the "Customer Login" button seems futile ...

Converting an object to JSON without prior knowledge of its type

Currently, I have a small program that consists of two classes. One class serves as the entry point of my application and deals with commandline arguments upon startup, while the other class contains options that I need to serialize into JSON format for la ...

Changing a JSON dictionary column into separate key-value pairs in Redshift and Postgresql databases

My current setup in Redshift involves an id column and a JSON dictionary stored as a string: id data 1 {'1': 'true', '2':'false'} 2 {'1': 'false', '3':'true'} I am looking to ...

The password encryption method with "bcrypt" gives an undefined result

import bcrypt from 'bcrypt'; export default class Hash { static hashPassword (password: any): string { let hashedPassword: string; bcrypt.hash(password, 10, function(err, hash) { if (err) console.log(err); else { ha ...

An issue has arisen: It seems that properties of null cannot be accessed, particularly the 'toISOString' property

After upgrading the dependencies in my package.json to their latest versions, I encountered an error while accessing a page that calls this data. Given that the dependencies were outdated by at least 2 years or more, I suspect the issue lies with the updat ...

What could be causing the JSON data to not be successfully transformed into an array in this particular scenario?

Here is the code snippet I am currently working with: $json_body = $application->request->getBody(); /*echo "JSON Body : ".$json_body; die; prints following data : JSON Body : { “current_user_id”:901 "user_id":990 } */ $request_da ...

The Angular Animation constantly resets with each new action taken

In my Angular project, I am working on a scaling animation for a list. I want the animation to only trigger when specific buttons (red and green) are pressed. Currently, the animation restarts regardless of what I click on. Can anyone help me troubleshoot ...

I am interested in creating JSON data

Below is the provided json data: { "id": 0, "isLeaf": false, "name": "root", "children": [ { "id": 3, "isLeaf": false, "name": "Node 2", "pid": 0, "disabled": true }, { "id": "new5", "isLeaf": ...

The third-party API is unable to access a class within a multi-module Maven project

Within my multi-module Maven project, I have included the JSON-IO dependency in the dao module. However, when attempting to deserialize my object, an error is thrown: Exception in thread "main" com.cedarsoftware.util.io.JsonIoException: Class listed in @t ...

Angular displays an error message and applies an invalid class when a form is submitted

I have created a form in Angular(5) using a template-driven approach. My goal is to display error messages and apply different styles to the input fields when they are invalid, especially when the form is submitted. Currently, I am able to achieve this fu ...

The data path "" must not contain any extra properties, such as dryRun

Just recently, I updated my MAC to the newest version of Angular 6.0.4. Upon entering the following command in Terminal: ng new happiness I encountered the following error: Schematic input does not validate against the Schema: {"dryRun":false,"version": ...

Angular: Autocomplete field automatically shifts focus when an item is removed

I am currently working on an Angular 2 application that utilizes PrimeNG components. One of the UI features includes an autocomplete component with multi-select functionality (p-autoComplete) similar to the one showcased in the official documentation: < ...