Struggling to fill tables from database in Angular. Encountering an issue: Error message stating "Error trying to diff '[object Object]'. Only arrays and iterables are permitted"

Despite encountering similar questions, none have successfully resolved my issue. Any assistance would be greatly appreciated. I am currently attempting to populate a table with data from my database. While I can successfully log the information, I encounter an error when trying to iterate through it.

Admin.HTML

    <div class="col">
      <button class="btn btn-primary" (click)="getData()">Customer Data</button>
    </div>
    <div class="col-sm-8 col-md-8">
      <table class="col table table-striped">
        <thead>
          <tr>
            <th scope="col-2">Name</th>
            <th scope="">Phone Number</th>
            <th scope="col-2">Email</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let customer of customers">
            <th scope="row">{{ customer.name }}</th>
            <td>{{ customer.number }}</td>
            <td>{{ customer.email }}</td>
          </tr>
        </tbody>
      </table>
    </div>

admin.ts

import { Component, OnInit } from '@angular/core';
import { Response } from '@angular/http';

import { CustomerData } from '../customer.service';

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {
  customers = [];

  constructor(private customerData: CustomerData) { }

  ngOnInit() {
  }

  getData() {
    this.customerData.getData()
    .subscribe(
      (customers: any[]) => this.customers = customers,
      (error) => console.log(error)
    )
  }
}

service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { FormGroup } from '@angular/forms';
import { map } from 'rxjs/operators';


@Injectable()
export class CustomerData {
    constructor(private http: Http) {}
    getData() {
        return this.http.get('link yo database')
        .pipe(map(
            (response: Response) => {
                const data = response.json();
                return data.result || data || [];
            }
        ));
    }
}

Answer №1

It appears that the data retrieved from your database is not in array format, which means it will not be iterable with *ngFor. The response seems to be an object or some other type of data structure.

To assist you further, I have set up a simple Stackblitz demo: https://stackblitz.com/edit/angular-ivy-ap58xs?file=src%2Fapp%2Fcustomer.service.ts

Feel free to check it out and see if it helps with your issue.

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

Exploring the functioning of Dependency Injection in components that are dynamically loaded

Given the setup of my components and services, with both Module A and B being lazy loaded, I have a scenario where the component container in Module A is dynamically loading Component B1. How does dependency injection work in this case? Does it look for de ...

Stylesheets per module in Angular 2

For my website design, I've decided to adopt a modular structure using sass. To ensure consistency throughout the module, instead of defining stylesheets at the component level, I plan to define them at the module level and import them into each compo ...

Changing the ngModel value within ngFor loop

I am working on a project where I need to display a list of grades from an object called 'grades'. Additionally, I want to integrate a slider component for each grade, with the value of the slider corresponding to a predefined list. However, it s ...

What is the best way to import multiple classes from a module folder in Angular2 using TypeScript?

In my Angular2 application, I have organized my modules as follows: /app /content /models resource.ts container.ts entity-type.ts index.ts /services /whatever ...

Tips for effectively locating code within a web browser's code base

Struggling as a new programmer in a new job with a fresh codebase, I am finding it difficult to connect the code to the webpage I am currently on. What methods can I use to locate the relevant HTML in the codebase that is being rendered in the web browser? ...

Using Angular to dynamically access component properties

Seeking assistance with creating dynamic Tabs in TabView of PrimeNG. The components are displaying properly, but I am unsure how to access their properties. I am following the guidelines provided at https://angular.io/guide/dynamic-component-loader and us ...

Checking the version listed in the package.json file within an Angular NX monorepository

As I work on transitioning an Angular monolith app into an Angular NX monorepo, one issue I've encountered involves the footer component. In the monolithic version, the footer accesses the 'version' in the package.json file. However, since t ...

Exploring the New Features of Angular 13 with Typescript, Regular Expressions, and

Currently, I am working on an Angular 13 project and I am trying to create a directive that will only allow users to type numbers and '/' in my date input field format of dd/mm/yyyy. Below is the regular expression (Regx) that I am using: if (!St ...

Issue: InjectionToken USE_DEFAULT_LANG not found in providers

Exploring angular 4 jasmine unit testing for the first time! Seeking assistance to achieve complete test coverage for my connected component. Despite adding child dependencies for the translate module, encountering Error: No provider for InjectionToken U ...

How Angular 2's change detection system causes unnecessary DOM refreshing

My application is currently in the live beta stage and I am focused on improving its performance. One issue that has caught my attention is the flickering of images within a table. Upon investigation, I discovered that the DOM is continuously refreshing, e ...

The variable <variable> is not meeting the 'never' constraint. Error code: ts(2344)

Currently, I am attempting to utilize Supabase alongside TypeScript. However, I encounter an error when trying to use functions like insert(), update(), upsert(), etc. Specifically, the issue arises when declaring the object I want to declare: "Type & ...

How can I toggle the visibility of a div after the DOM has finished loading?

I was experimenting with a radio button on the interface linked to a property in the typescript file that controls the visibility of another div. However, I noticed that both *ngIf="isFooSelected" and [hidden]="!isFooSelected" only function upon initial pa ...

Before fetching the data from firebase in Angular 2, it is crucial to ensure that the code is properly

I'm facing an issue when trying to retrieve data from Firebase. It successfully retrieves the data, but it takes a few seconds to do so. In the meantime, the code continues running and the variable's value becomes null. Why is this happening? Is ...

Is there a way to implement ngModel within a loop?

I am facing a challenge in my Angular application where I need to change the value of ngModel based on the items in the license. However, while looping through my .ts file, I noticed that ngModel is taking the last value of test even for items not present ...

Vitest encountered an issue fetching a local file

I am currently working on testing the retrieval of a local file. Within my project, there exists a YAML configuration file. During production, the filename may be altered as it is received via a web socket. The code functions properly in production, but ...

What is the best method for incorporating Angular 2 files into a Django template?

My application structure is set up like this: ├── project | |── templates │ │ └── index.html │ ├── __init__.py │ ├── models.py │ ├── urls.py │ ├── serializers.py │ ├── views.py ...

Angular: The specified function name cannot be called

My approach involves assigning an imported function to a component property within the constructor so that it can be utilized in the template. Although builds are successful, an error appears in my editor (Visual Studio Code with Angular Language Service) ...

Custom navigation button in Angular's FullCalendar header

In my Angular project, I am utilizing fullcalendar with both week and month views, and it has been working smoothly so far. Now, my aim is to modify the text displayed on the navigation button. As per the documentation, I have created custom buttons as fo ...

using a shared templateurl for numerous components

In my search for the optimal solution to this issue, I have come across a scenario where I have 4 components that share the exact same HTML structure, but the logic in the TypeScript file varies. My goal is to have all 4 components utilize the same HTML t ...

Validating Angular Forms using NgIf

Currently working on a form that includes a textbox for the user's first name. Implementing verifications. Using a basic form with a single error line, everything functions correctly: <div class="col-12 col-md-6"> <inpu ...