【问题标题】:Angular ngfor doesnt render listAngular ngfor 不呈现列表
【发布时间】:2020-12-11 14:13:39
【问题描述】:

我在带有数组的 Html 页面中使用 NGFor,但出现以下错误。

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,组件将其转换为数组。

【问题讨论】:

  • 请指定this.productService.getProductsNewest()返回的数据结构;
  • 如果我不得不猜测,因为您没有包含该代码,我会说 getProductsNewest 返回一个可观察的或承诺,而不是一个数组。
  • 我已经编辑了帖子并添加了一些代码。
  • console.log(this.productService.getProductsNewest()) 请告诉结果
  • 返回新闻集时的 99% 异步代码。你需要订阅 observable

标签: arrays angular typescript ngfor angular-ng-if


【解决方案1】:

使用“异步”管道订阅并保留 TS 文件原样。

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

【讨论】:

    【解决方案2】:
     public getProductsNewest(): Observable<YourType> {
        return this.http.get(`${this.baseUrl}/products/newest`);
      }
    
    
    
     public ngOnInit() {
        this.newestProducts = [];
         this.productService.getProductsNewest().subscribe(newest => {
         this.newestProducts = newest
           }, error=> console.log(error) ;
     
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 2019-11-04
      相关资源
      最近更新 更多