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

Python function to unroll nested JSON and extract all keys and nested keys

I am looking for a way to parse keys and nested keys from JSON data. Let me provide an example: {"Field1":"a","Field2":"b","Field3":"c","AdditionalInfo":{"Name":"foo" ...

Converting nested JSON structures into a PySpark DataFrame

Looking for a simple way to convert the provided JSON sample into a PySpark dataframe? Input : { "user": { "1": { "name": "Joe", "age": 28 }, "2" :{ "name": "Chr ...

Struggling to get the Okta Auth0's AuthGuard to properly redirect to a specific route following a successful login request for a protected route

I have implemented Auth0 in my Angular application to authenticate users using the steps outlined below: Users visit the root page (e.g. ) and click on the Login button via their Google account. Users are redirected to the Auth0 login page through the Goo ...

Is it better to use a setter instead of an isMethod with @JsonIgnore in JSON serialization and

Here is a snippet of my custom HouseJPAImpl class: public class HouseJPAImpl implements House { public RoomJPAImpl room; public RoomJPAImpl getRoom(){ return this.room; } public void setRoom(RoomJPAImpl room){ this.room = room; } @Override public bool ...

Deploying Angular to a shared drive can be done in a

My angular.json file contains the following line: "outputPath": "Y:\Sites\MySite", After running ng build, I encountered the error message: An unhandled exception occurred: ENOENT: no such file or directory, mkdir 'D:& ...

What could be causing the issue with receiving deserialized data in my WebAPI?

I have a straightforward WebAPI application. Here is an excerpt from my controller: [HttpPost] public ActionResult DoSomeWork(string stringParam, DTOObject dto) { // Some work happens here } My console application is calling this method as follows: ...

Make sure to call the loader function in React Router only when there are path params present

I'm currently implementing the new React Router, utilizing loader functions to fetch data based on the loaded element. My goal is to have certain APIs called regardless of the route, with additional APIs triggered for specific routes. However, I&apos ...

Is it secure to utilize Http.Get (with parameters) for accessing WebApis in Angular 2/4?

When calling a Web API in Angular, is it safe to use Http Get with passwords included in the fields? Or would it be more secure to utilize Http Post instead? Check out this example on how to execute an Http.get request in Angular: http.get(baseUrl + &apo ...

typescript is reporting that the variable has not been defined

interface User { id: number; name?: string; nickname?: string; } interface Info { id: number; city?: string; } type SuperUser = User & Info; let su: SuperUser; su.id = 1; console.log(su); I experimented with intersection types ...

Retrieve data from a JSON object and separate them into columns based on a specific identifier

I am working with a database that stores JSON arrays of objects in a column. My goal is to create columns based on the keys of these objects when the object's id meets certain criteria. The structure of my documents table is as follows: id | name ...

Is it possible for me to make the default export anonymous?

Why bother naming the export if you already have a file with the default export name? This seems redundant and goes against the DRY principle. While there is a rule that discourages anonymous default exports, how can we enforce an error when someone does ...

Guide to configuring a not null property in Typescript Sequelize:

Hello there! I am trying to figure out how to set a not null property using TypeScript Sequelize. I have tried using the @NotNull decorator, but unfortunately it does not seem to be working. The errors I am encountering are as follows: Validation error: W ...

Received a 302 status code during an AJAX request and unable to reach the post action. Any suggestions on how to resolve

I am encountering a 302 error when making an ajax request in my view. The code I have written does not hit the controller action and in the network header, I see status code 302 displayed. Can someone please help me understand why this error is occurring ...

Union does not contain the specified property in Typescript

Here are the types that I have: Foo { foobar: any } Bar { fooBarBar: any; } I want to use a function defined like this: this.api.submit(param: Foo | Bar) When trying to use it, I encountered an issue: this.api.submit(param.foobar) // does no ...

What is the best method for inserting a hyperlink into the JSON string obtained from a subreddit?

const allowedPosts = body.data.children.filter((post: { data: { over_18: any; }; }) => !post.data.over_18); if (!allowedPosts.length) return message.channel.send('It seems we are out of fresh memes!, Try again later.'); const randomInd ...

Set up variables during instantiation or within the class declaration

Is there a preferred way to initialize class variables in ReactJS with TypeScript - in the constructor or when declaring the variable? Both methods seem to work equally well and result in the same transpiled javascript. export class MyClass extends Reac ...

Having trouble accessing JSON file again: "Encountered unexpected end of input error"

I have set up a cron-based scheduler to periodically retrieve JSON data from an external API every 2 minutes. The process involves writing the data to a file, reading it, cleaning it, and then storing it in a MongoDB collection. Everything works smoothly o ...

What is the best way to sequentially invoke methods in Angular?

When initializing in the ngOnInit() method, I need to call several methods synchronously. However, all these methods involve asynchronous calls to an API. The challenge is that certain variables must be set before proceeding with the subsequent methods. Un ...

Navigating in Angular 2.0.0-rc1 with routes and setting a default route using use

Is it true that "useAsDefault" has been removed in angular2.0.0-rc1? Any suggestions for a workaround? I noticed in the Angular documentation they are using the OnInit method... Do subroutes still function with the /... notation? Thanks ...

Serialization of Serializable Generic Types in Kotlin

Dealing with Kotlin serialization can be quite challenging! How can I make Kotlin understand that the values in my properties map are either primitives or classes annotated with @Serializable? I'm attempting to transform a class similar to this: clas ...