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-If, я получаю ту же ошибку.

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

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;

}

Методы службы возвращают любое, а компонент преобразует его в массив.


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% асинхронный код при возврате новых наборов. Вам нужно подписаться на наблюдаемые   -  person Damien    schedule 22.08.2020
comment
Что-то еще, вы должны ввести свои HTTP-вызовы, например: 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