Angular ngfor не изобразява списък

Използвам NGFor в моята Html страница с масив, но получавам следната грешка.

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)

Моят ngFor изглежда така:

 <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>

и моят ts файл изглежда така:

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) {  // customize default values of carousels used by this component tree
    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']);
  }
}

Може ли някой да ми каже защо получавам тази грешка и как да я разреша? Ако използвам ng-Ако получа същата грешка.

Ето моята услуга:

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) { }

  public getProductById(id: number): any {
    return this.http.get(`${this.baseUrl}/products/${id}`);
  }

  public getProductByName(name: string): any {
    return this.http.get(`${this.baseUrl}/products/${name}`);
  }

  public getProductsList(): any {
    return this.http.get(`${this.baseUrl}/products`);
  }

  public getProductsNewest(): any {
    return this.http.get(`${this.baseUrl}/products/newest`);
  }

  public getProductsRandom(): any {
    return this.http.get(`${this.baseUrl}/products/random`);
  }

  public getProductsBySubcategorie(subcategorie: string): any {
    return this.http.get(`${this.baseUrl}/products/subcategorie/${subcategorie}`);
  }

  public getProductsBySubcategorieId(id: number): any {
    return this.http.get(`${this.baseUrl}/products/subcategorie/${id}`);
  }

  public getProductsByCategorie(categorie: string): any {
    return this.http.get(`${this.baseUrl}/products/categorie/${categorie}`);
  }

  public getProductsByCategorieId(id: number): any {
    return this.http.get(`${this.baseUrl}/products/categorie/${id}`);
  }

  public getProductsBySubcategorieAndCategorie(subcategorie: string, categorie: string): any {
    return this.http.get(`${this.baseUrl}/products/subcategorie/${subcategorie}/categorie/${categorie}`);
  }

}

и това е dto:

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;

}

Методите на услугата връщат any и компонентът го прехвърля към масив.


person tobias    schedule 22.08.2020    source източник
comment
Моля, посочете структурата на данните, върнати от this.productService.getProductsNewest();   -  person Jasdeep Singh    schedule 22.08.2020
comment
Ако трябваше да гадая, тъй като не сте включили този код, бих казал, че getProductsNewest връща наблюдаем или обещание, а не масив.   -  person Ingo Bürk    schedule 22.08.2020
comment
Редактирах публикацията и добавих някакъв код.   -  person tobias    schedule 22.08.2020
comment
console.log(this.productService.getProductsNewest()) и кажете резултата, моля   -  person pc_coder    schedule 22.08.2020
comment
99% асинхронен код при връщане на новини. Трябва да се абонирате за observable   -  person Damien    schedule 22.08.2020
comment
Нещо друго, трябва да въведете своите http get извиквания, т.е. this.http.get‹Product› или this.http.get‹Product[]›, типовете ще се издигнат до съответните променливи във вашия компонент и като цяло всичко ще бъде тип сейф.   -  person wlf    schedule 22.08.2020


Отговори (1)


Използвайте 'async' тръба, за да се абонирате и оставете TS файла такъв, какъвто е.

<div class="flex-container wrap" *ngFor="let item of newestProducts | async">
person wlf    schedule 22.08.2020