Encountering an issue in Angular9 where it cannot find a differ supporting an object of type 'object'. NgFor is limited to binding with Iterables like Arrays

I have developed a straightforward application for calling backend services using HttpClientModule. However, I am encountering an issue where the data is not displaying in the log. Below are the steps that I followed, and I am working with Angular-9.

Could you please review the code?

Thank you in advance.

  1. app.module file
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule} from '@angular/common/http';
import {RestAPIServices} from './services/rest-api.service';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [RestAPIServices],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. model.ts
export class Employee{
    id:number;
    name:string;
    gender:string;
    email? :string; // ? means optional property
    mobile:string;
    department:string;
    isActive:boolean;
    photo? :string;
}
  1. service.ts
import {Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import {HttpClient} from '@angular/common/http';
import { Employee } from '../models/employee.model';

@Injectable()
export class RestAPIServices{

    constructor(private httpClient:HttpClient){}

   getEmployee():Observable<Employee[]>{
    //this.httpClient.get<Employee[]>("http://127.0.0.1/angularCRUDservices/user/getEmployees").subscribe(res=>  console.log(res));
    return this.httpClient.get<Employee[]>("http://127.0.0.1/angularCRUDservices/user/getEmployees");
   }

}
  1. app.component.ts
import { Component } from '@angular/core';
import {RestAPIServices} from './services/rest-api.service';
import {Employee} from './models/employee.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  listEmployee : Employee[];
  title = 'simple-rest-app';

  constructor(private _employeeService:RestAPIServices){}
  ngOnInit(){

    this._employeeService.getEmployee().subscribe(
      data=>{
        console.log(data)
        this.listEmployee = data;
      }
    )

    console.log(this.listEmployee);
  }

}

The service has been tested using Postman and is functioning correctly.

{"response":[{"id":"1","name":"Anand","gender":"Male","email":"example@example.com","mobile":"111111111","department":"2","isActive":"1","photo":"assets\/images\/emp1.jpg"},{"id":"2","name":"Kiran","gender":"Female","email":"example2@example.com","mobile":"2222222222","department":"2","isActive":"1","photo":"assets\/images\/emp1.jpg"},{"id":"3","name":"Ravi","gender":"Male","email":"example3@example.com","mobile":"3333333333","department":"2","isActive":"1","photo":"assets\/images\/emp2.jpg"},{"id":"4","name":"Kumar","gender":"Male","email":"example4@example.com","mobile":"4444444444","department":"3","isActive":"1","photo":"assets\/images\/emp4.jpg"}]}

Answer №1

Seems like the issue lies in the server response format, which is currently an object and not an array.

// Attempt to switch from
this.httpClient.get<Employee[]>(...);

// to
this.httpClient.get<{ data: Employee[] }>(...).pipe(
  map(response => response.data)
);

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

Show a particular set of data in the template

My Angular application consists of a sender and a receiver component that are linked through the data service. The sender template includes an input field where users can enter a number, which is then transmitted to the receiver when a button is clicked. T ...

I am facing difficulty transitioning from iframe to the Angular App

I have attempted various solutions from stack overflow to switch to an iframe using ProtractorJS, but none of them have successfully worked for me. I am seeking help from someone who has faced a similar issue and could provide some guidance. The Issue: Wh ...

Transferring various sets of information into a single array

In an attempt to generate JSON data in an array for passing to another component, I followed a method outlined below. However, being relatively new to this field, my execution may not have been optimal as expected. employeeMoney: any[] = []; employeeId: an ...

Navigating to Angular component from Mapbox popup

I'm currently working on a mobile app with Ionic and Angular. The app features various Mapbox markers that open custom popups when clicked, each displaying unique content. I want the button within the popup to redirect users to a page with more inform ...

Steps for resetting the TypeScript version in VSCode:

I've recently been immersed in a typescript project using Visual Studio Code. Our project relies on an older version of typescript (1.8.10), which has been working seamlessly so far thanks to having the appropriate ts compiler package installed locall ...

Anticipating the outcome of various observables within a loop

I'm facing a problem that I can't seem to solve because my knowledge of RxJs is limited. I've set up a file input for users to select an XLSX file (a spreadsheet) in order to import data into the database. Once the user confirms the file, v ...

Generate a nested array of objects by recursively looping through an array of objects

Imagine I have an array of objects structured like this: myArr = [ { "id": "aaa.bbb" }, { "id": "aaa.ccc" }, { "id": "111.222" }, { "id": "111.333" }, ] I aim t ...

Tips for retrieving only the changes or updates from DynamoDB streams

Currently, I am faced with a scenario where I must comprehend the distinction between NEW_IMAGE and OLD_IMAGE on dynamoDB streams. As per the information available at: https://aws.amazon.com/blogs/database/dynamodb-streams-use-cases-and-design-patterns/ ...

Issues arise with the escape key functionality when attempting to close an Angular modal

I have a component called Escrituracao that handles a client's billing information. It utilizes a mat-table to display all the necessary data. When creating a new bill, a modal window, known as CadastrarLancamentoComponent, is opened: openModalLancame ...

Remove an item from an array within Express using Mongoose

{ "_id": "608c3d353f94ae40aff1dec4", "userId": "608425c08a3f8db8845bee84", "experiences": [ { "designation": "Manager", "_id": "609197056bd0ea09eee94 ...

Launching an Angular application in a universal environment on Azure's service

My angular app is configured with Angular Universal. After the build pipeline, I have a server folder that I understand is necessary. However, when I use my app without server-side rendering (SSR), I point the path in Azure App Settings to my browser folde ...

How to build a login page with a static header and footer using Angular2

For my latest project, I am currently in the process of developing an application using Angular2 and eclipse Neon. Utilizing angular-cli for this app, I am now focused on creating the login page. Within the app.component.html file, you will find the follow ...

What method can I use to reach the controller of a route that has been exported to another route?

I am currently incorporating nested routes in my TypeScript project. I have set up a router named review.route.ts with the following code snippet: > review.route.ts import { createReview } from "@controller..."; const reviewsRouter = Router() as Expre ...

What's the Best Way to Add a Custom Flag to the `nx angular serve` Command Without Triggering an Error?

When running the nx angular serve command, I want to add my custom flag (-t example). But when I try this, I get an error message from nx that says: 't' is not found in schema To address this issue, I plan to capture this flag in proxy.mjs an ...

Utilizing Array.every to refine a union of array types, narrowing down the options

I need to narrow down the type of a variable that is a union of different array types in order to run specific code for each type. I attempted to use Array.every along with a custom type guard, but encountered an error in TypeScript stating "This expressio ...

Guide to setting a default value in a asynchronous list within an ng-select (Angular 2+, ng-select, and rxjs)

I recently started using ng-select and incorporated the typeahead feature to fetch server data as the user types. This is how I implemented it: I created an observable for the list of agents which gets updated whenever a new string is inserted agents$: Ob ...

A versatile sorting algorithm

Currently, I am working on converting the material UI sorting feature into a generic type. This will enable me to utilize it across various tables. However, I have hit a roadblock in implementing the stableSort function, which relies on the getSorting func ...

Setting the Formgroup status to Invalid will only occur if there are errors in multiple fields, not just one

I'm having an issue with my form where setting passportrank as error does not change the formgroup status to Invalid. Additionally, when I navigate to the next section, the inline error message of "You are not eligible" also gets cleared. ngOnInit() ...

Is it possible for me to create an interface that enables me to invoke a custom method on particular strings?

My database returns objects structured like this: interface Bicycle { id: string; created_at: string; } The data in the created_at field is a machine-friendly date that I need to convert into a Date object for localization: new Date(bike.created_at). ...

choosing between different options within Angular reactive forms

I am attempting to create a select element with one option for each item in my classes array. Here is the TypeScript file: @Component({ selector: 'app-create-deck', templateUrl: './create-deck.component.html', styleUrls: [' ...