Angular ngFor not displaying the list

I'm encountering an issue with my HTML page where I'm using NGFor with an array. The error message I receive is as follows:

landingpage.component.html:142 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
    at NgForOf.ngDoCheck (common.js:4355)
    at checkAndUpdateDirectiveInline (core.js:33470)
    at checkAndUpdateNodeInline (core.js:46564)
    at checkAndUpdateNode (core.js:46503)
    at debugCheckAndUpdateNode (core.js:47529)
    at debugCheckDirectivesFn (core.js:47472)
    at Object.updateDirectives (landingpage.component.html:142)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:47460)
    at checkAndUpdateView (core.js:46468)
    at callViewAction (core.js:46834)

My ngFor implementation looks like this:

 <div class="flex-container wrap" *ngFor="let item of newestProducts">
          <div class="card flex-item">
            <img src="{{ item.pictureUrl }}" class="card-img-top"
                 alt="...">
            <div class="card-body">
              <p class="card-title">{{ item.aktPrice }}€</p>
              <p class="card-text">{{ item.productname }}</p>
              <a href="/details/{{item.id}}" class="btn btn-primary productbutton"><p class="productbuttontext">Zum
                Produkt</p></a>
            </div>
          </div>

Here's how it's defined in my TypeScript file:

export class LandingpageComponent implements OnInit {
  public images = [944, 1011, 984].map((n) => `https://mdbootstrap.com/img/Photos/Horizontal/City/4-col/img%20(60).jpg`);
  public newestProducts: Product[];
  public randomProduct: Product;
  public gutscheine: Gutschein[];
  public submitted = false;

  constructor(private productService: ProductService, private gutscheinService: GutscheinService,
              private router: Router, config: NgbCarouselConfig) {  
    config.interval = 100;
    config.wrap = false;
    config.keyboard = false;
    config.pauseOnHover = false;
  }

  public ngOnInit() {
    this.newestProducts = [];
    this.newestProducts = this.productService.getProductsNewest();
    this.gutscheine = this.gutscheinService.getGutscheine();
    this.randomProduct = this.productService.getProductsRandom();
  }

  public gotoList() {
    this.router.navigate(['/landingpage']);
  }
}

I'm unable to figure out why I'm getting this error and how to resolve it. When trying to use an ng-If instead, the same error occurs.

Additionally, here is the service code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ProductService {
  private baseUrl = 'http://localhost:8080/priceoffer24/api/product';

  constructor(private http: HttpClient) { }

  // Methods truncated for brevity...
}

Lastly, this is the DTO structure:

import {Categorie} from './categorie';
import {Prices} from './prices';

export class Product {
  public id: number;
  public description: string;
  public productname: string;
  public link: string;
  public pictureUrl: string;
  public aktPrice: string;

}

The methods within the service return any, which is being cast to an array in the component.

Answer №1

Utilize the 'async' pipe for subscribing without any changes to the TS file.

<div class="container-fluid" *ngFor="let product of latestItems | async">

Answer №2

 function retrieveNewestProducts(): Observable<ProductType> {
    return this.http.get(`${this.baseUrl}/products/newest`);
  }



 function initializePage() {
    let latestItems = [];
     productService.retrieveNewestProducts().subscribe(response => {
     latestItems = response
       }, error=> console.log(error) ;
 
  }

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

A guide to navigating a JSON array

Utilizing node js, I have extracted the following array by parsing through multiple json files to find a specific value. My json files consist of a collection of IDs with their respective status: isAvailable or undefined. https://i.sstatic.net/AlpVk.png ...

Scouring the Active Directory with AngularJS

I am still fairly new to working with Angular, and I have a web application that requires users to input names and locations. One common issue raised by users is the inability to search for people using active directory. Is there a way for me to implemen ...

Retrieving individual data elements from an array with the help of the .find() method

I am struggling to display specific details of an object within an array by using .find() method, but I keep receiving undefined as the output. Below is the code snippet where I attempted this, when I log the ID, I can see a value, however, when I try to ...

How can I target and focus on a dynamically generated form in Angular 4/Ionic3?

One of the challenges I'm facing is dealing with dynamically created forms on a page. Each row consists of inputs and a button. Is there a way to select/focus on the input by clicking on the entire row (button)? It should be noted that the number of r ...

Understanding the integration of jQuery html attributes with Angular2

I am encountering an issue with a library that requires me to include the tag below in my image: data-zoom-image When I add this tag to my image: <img class="larger-picture" [src]="'images/'+item.picture" align="middle" data-zoom-image="&ap ...

There seems to be a problem fetching the WordPress menus in TypeScript with React and Next

Recently I've started working on a project using React with TypeScript, but seems like I'm making some mistake. When trying to type the code, I encounter the error message: "TypeError: Cannot read property 'map' of undefined". import Re ...

Definitions for Typescript types that describe a custom hook responsible for fetching a specific part of the Redux state

I've created a custom hook called useReduxState to fetch a specific piece of state from Redux like so: const STATE_A = useReduxState("STATE_A"); Now, I'm running into issues when trying to integrate Typescript. These are the types I a ...

Tips for arranging, categorizing, and separating the array in alphabetical order using Angular 2+

I am looking to organize the buttons' content alphabetically into groups A-H, I-Q, and R-Z. The code I'm using is in Angular2+. https://i.sstatic.net/pPCBO.png My array: this.dropdownList = [ { item_text: 'Organisation' }, ...

Is it possible to store a character as an integer array in C? If so, what is the process for converting

I am struggling to comprehend a portion of the C code and convert it into C# code. This section appears to be a char array represented with integers. Could someone please advise on how to translate this into C# code? Thank you in advance! static const ch ...

Showing a header 2 element just once using both *ngFor and *ngIf in Angular

I have an array of words with varying lengths. I am using ng-For to loop through the array and ng-if to display the words based on their lengths, but I am struggling to add titles to separate them. Expected Outcome: 2 letter words: to, am, as... 3 lette ...

I'm curious if there is a method to implement Angular Datatables that includes a filter for every column in a more streamlined and efficient manner?

Incorporating Angular 7 and Angular DataTables "the angular way", I aim to implement individual column filters similar to "Individual column searching" as demonstrated here: , which is presented as a non-angular approach. My attempts to merge "the angular ...

Unable to create property within array in model

I am facing an issue while trying to access the name property of an array called Model[] generated from my Model.ts file. When attempting to use it in my app.component, I receive an error stating that the property 'name' does not exist on type Mo ...

Angular Material: Enable Window Dragging Across Multiple Monitors

Exploring the usage of Angular Material Dialog or any other Popup Window Component. The functionality is mostly working as expected, with the exception of the last point. a) The original screen should not have a grey overlay, b) Users should be able to i ...

Tabs justified are not constrained by width

Utilizing Bootstrap 3, I aim to have the Tabs align perfectly with the full content. The use of nav-tabs can be observed in the code below. It may seem a bit unusual due to my implementation of Angular 4 and the code being copied from Dev Tools. <ul cl ...

Transferring information between components is made easy with ng-content

In my application, I have a set of components that are used to create cards: <app-card-container> <app-card-title>Card title</app-card-title> <app-card-body> // some content </app-card-body> </app-card-con ...

"Customizing the template of the Angular Material 2 datepicker: A step-by-step

Looking to make changes to the templates of the angular 2 material date-picker? These templates are located within various internal components in @angular/material/esm5/datepicker.es5.js. One option is to directly modify the template in the node package, ...

Generating typescript definitions for Polymer 2.4 packages

According to information provided in the latest announcement, declarations are now automatically generated from the Polymer source. I recently upgraded to Polymer 2.4 and encountered an error during project build due to a missing typescript definition fil ...

Tips for setting up a mdl-dialog using a declarative approach

I want to incorporate a mdl-dialog into my component following the example provided here: However, when I try to do so, the compiler throws an error stating: Can't bind to 'mdl-dialog-config' since it isn't a known property of ' ...

Error in ng2-translate: TranslatePipe.transform cannot access the property 'subscribe' as it is undefined

I have been utilizing ng2-translate within my Angular 5 project and I am currently in the process of setting up a unit test for a specific component. Typically, I import TranslateModule.forRoot( *...* ) in my Tests and everything runs smoothly when using t ...

There is no value inputted into the file

I'm facing a small issue while trying to retrieve the value from my input of type="file". Here is the code snippet: <tr ng-repeat="imagenDatos in tableImagenesPunto | filter: busquedaDatosPunto " > <td>PNG</td> <td>{{imag ...