Encountering a problem while implementing ngFor in Angular 4

Issue with ngFor Loop in Angular 4

Does anyone have insight into why this error is appearing in the console despite data being displayed?

The data is showing, but an error is still being thrown

empresas = <Empresa> {};

  constructor(private service: Service) { }

  ngOnInit() {
    this.service.getEmpresas().subscribe((res) => {
        this.empresas = res
    })
  }

Template

<tr *ngFor="let empresa of empresas">
            <td>
              {{ empresa.created_at }}
            </td>
            <td>
              {{ empresa.nome }}
            </td>
            <td class="text-center">
              {{ empresa.protocolo }}
            </td>
            <td class="text-right">
              <a [routerLink]="['/resultado']">Explore Results</a>
            </td>
          </tr>

HistoricoComponent.html:37 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays. at NgForOf.webpackJsonp.../../../common/@angular/common.es5.js.NgForOf.ngOnChanges (common.es5.js:1681) at checkAndUpdateDirectiveInline (core.es5.js:10833) at checkAndUpdateNodeInline (core.es5.js:12332) at checkAndUpdateNode (core.es5.js:12271) at debugCheckAndUpdateNode (core.es5.js:13132) at debugCheckDirectivesFn (core.es5.js:13073) at Object.eval [as updateDirectives] (HistoricoComponent.html:37) at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13058) at checkAndUpdateView (core.es5.js:12238) at callViewAction (core.es5.js:12603)

service

getEmpresas(): Observable<any> {
        const headers = new Headers();
        return this.http.get(`${MEAT_API}/empresas`,
            new ResponseOptions({headers: headers}))
            .map(response => response.json())

    }

Answer №1

The cause of this issue is that you are attempting to iterate over a variable that is not iterable.
This is why ngFor is failing. Make sure that 'empresas' is an array of Empresa. Also, try logging the data received from the API response to check if it consists of an array of Empresa objects. The error message provides a clue.

NgFor only works with Iterables like Arrays

Answer №2

After calling the getEmpresas function, the returned data stored in the variable res is an Object {}

this.service.getEmpresas().subscribe((res) => {
    this.empresas = res
})

The *ngFor directive is unable to iterate over Objects (unless a KeysPipe is utilized). Therefore, it is recommended to modify the getEmpresas() function to return an array or implement the provided KeysPipe.

For example:

import {PipeTransform, Pipe} from "@angular/core";

@Pipe({
  name: 'KeysPipe'
})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]});
    }
    return keys;
  }
}

Usage:

*ngFor="let empresa of empresas | KeysPipe"
{{empresa.key}} {{empresa.value}}

Answer №3

You have set the return value of getEmpresas() as an object, and *ngFor cannot iterate through an object. To solve this issue, you need to initialize an empty array by declaring empresas: any=[].

this.service.getEmpresas().subscribe(res=>this.empresas=res);

In your template, you can loop through the array using *ngFor like this:

<tr *ngFor="let empresa of empresas">
>     <td>
>         {{ empresa.created_at }}
>     </td>
>     <td>
>         {{ empresa.nome }}
>     </td>
>     <td class="text-center">
>         {{ empresa.protocolo }}
>     </td>
 </tr>

Answer №4

One possible solution is to use this code:

companies : any = [];

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 ensure that my variables are properly differentiated in order to prevent Angular --prod --aot from causing empty values at runtime?

While testing my code locally in production, the functions I've written are returning the expected values when two parameters are passed in. However, after running ng build --prod --aot, the variable name within the functions changes from name to t. ...

Guide to aligning a fraction in the center of a percentage on a Materal Design progress bar

Greetings! My objective is to create a material progress bar with the fraction displayed at the top of the percentage. Currently, I have managed to show the fraction at the beginning of the percentage. Below is the code snippet: <div class=" ...

Why are @Inject and Injectable important in Angular's Dependency Injection system?

constructor(private smartphoneService: smartphoneService) { } Although I am able to execute the code above without encountering any errors, I find myself pondering on the necessity of using @Inject and Injectable on services, Pipes, and other components. ...

I prefer the value to switch to false whenever I navigate to a new route and then return to the previous route, as the sidebar remains open

click here for image details view image description here Struggling to set the value as false when revisiting this site. Need assistance! Could someone lend a hand, please? ...

Connecting RxJS Observables with HTTP requests in Angular 2 using TypeScript

Currently on the journey of teaching myself Angular2 and TypeScript after enjoying 4 years of working with AngularJS 1.*. It's been challenging, but I know that breakthrough moment is just around the corner. In my practice app, I've created a ser ...

What could be causing the error in Angular 2 when using multiple conditions with ng-if?

My aim is to validate if the length of events is 0 and the length of the term is greater than 2 using the code below: <li class="more-result" *ngIf="events?.length == 0 && term.value.length > 2"> <span class="tab-content- ...

The issue arises when attempting to use the search feature in Ionic because friend.toLowerCase is not a valid function

I keep encountering an error message that says "friend.toLowerCase" is not a function when I use Ionic's search function. The unique aspect of my program is that instead of just a list of JSON items, I have a list with 5 properties per item, such as f ...

Discovering all images in Angular

I have a function that stores image data, including the name. Using *ngFor, I am able to fetch this data from the database and display it in boxes. HTML <div class="row tab-pane Galeria"> <div *ngFor="let product of products" (click)="Im ...

Trigger the Modal once the navigation step is completed

When navigating to a new page, I need to wait for the navigation process to complete in order for the modal template to be properly displayed on the destination page. public onOpenModal(item) { this.router.navigate([item.link]).then(() => { this. ...

p-menu fails to appear

I'm currently experimenting with Primeng and Angular 2 to put together a basic menu. Take a look at my code snippet: import {Component, OnInit} from '@angular/core'; import {Menu, MenuItem} from 'primeng/primeng'; @Component({ ...

What are the steps for creating a TypeScript version of a custom CKEditor5 build?

Currently, I am in the process of creating a personalized version of CKEditor5. By following the guidelines provided in the official documentation, I successfully obtained ckeditor.js. My goal now is to produce a typescript file (ckeditor.ts or ckeditor.d ...

Tips for assigning the 'store_id' value to a variable in Angular 6 within the Ionic4 environment

Trying to retrieve the store_id from the StorageService in Ionic4 (angular 6). Managed to retrieve the store_id using: let id = this.storageService.get('store_id'); id.then(data => { this.store.push(data) }); After pushing it into an ar ...

Error message: In my router module, Angular's 'Subject' is not subscribed to

Currently, I am utilizing a canActivateFn guard in my application where I am subscribing to a Subject. This particular Subject was instantiated in a separate service, and I'm perplexed as to why the subscription does not seem to trigger (the callback ...

Transform webservice data into TypeScript object format, ensuring mapping of objects from capital letters to camel case

Something peculiar caught my attention in my Angular2 TypeScript project. When objects are fetched from a web service, they have the type "Level" and the properties are in Pascal case. However, during runtime, I noticed that the properties of these Levels ...

Is there a more effective alternative to using the ternary condition operator for extended periods of time?

Do you know of a more efficient solution to handle a situation like this? <tr [style.background]="level == 'ALARM' ? 'violet' : level == 'ERROR' ? 'orange' : level == 'WARNING' ? 'yellow' ...

How do you implement an asynchronous validator for template-driven forms in Angular 2?

I have created a custom directive for my asynchronous validator: @Directive({ selector: '[validatorUsername]', providers: [{ provide: NG_ASYNC_VALIDATORS, useExisting: ValidatorUsernameDirective, multi: true }] }) export class ValidatorUsern ...

Error: The StsConfigLoader provider is not found! MSAL angular

I am currently using Auth0 to manage users in my Angular application, but I want to switch to Azure Identity by utilizing @azure/msal-angular. To make this change, I removed the AuthModule from my app.module and replaced it with MsalModule. However, I enco ...

Attempting to ensure that Angular 2 delays rendering until the necessary data has finished loading

Looking to efficiently load multiple XML files before the initial rendering? Here's a configuration snippet from app.module.ts: import { DataProvider } from './xml-provider' export function dataProviderFactory(provider: DataProvider) { r ...

Issue with NPM: Unable to locate the reference to 'Many' and the namespace '_' from the lodash library

I've been incorporating lodash into my angular2 project. Here are the commands I used: $ npm install --save lodash $ npm install --save @types/lodash Upon installing lodash, warning messages popped up for both the main library and the types: https: ...

Do I have to wait for the HTTP get request to access the fetched object property?

I am currently working with Angular and TypeScript on a dish-detail component that is accessed through 'dishes/:id' The dish object returned has a property called components, which contains an array of objects with two properties: id: type stri ...