无法使用ngfor以html格式打印列表

2skhul33  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(293)

我是新的Angular 和前端。我正在尝试调用RESTAPI来获取产品列表。然后我尝试在html页面中打印它们。
product.component.html

<div class="page-title">Product List</div>
<div class="bgblue">
    <div class="product-preview-container">
        <ul *ngIf="!emptyProductList">
            <p>Available Products</p>
            <li *ngFor="let product of products">
            <p>Product Name  : {{ product.productName }}</p>
            <p>Product Code  : {{ product.productCode }}</p>
            <p>Product Price : {{ product.productPrice }}</p>
            </li>
        </ul>
        <ul *ngIf="emptyProductList">
            <p>No Product Found  </p>
        </ul>
    </div>
</div>

product.component.ts

export class ProductComponent implements OnInit {

  errorMessage = '';
  emptyProductList = true;
  products: Product[];

  constructor(private productService: ProductService) {
    this.products = [];
  }

  ngOnInit() {
    console.log('Called ngOnInit method');
    this.productService.fetchProductList().subscribe(
      (productList: Product[]) => {
        this.products = productList; 
        if(this.products.length>0){
          this.emptyProductList = false;
          console.log('not empty');
        }       
      }, err => {
        this.errorMessage = err.error;
      })
  }

}

更新
产品服务

export class ProductService {

  constructor(private http: HttpClient, private adapter: ProductAdapter) { }

  fetchProductList(): Observable<Product[]> {
    return this.http.get(PRODUCT_LIST_API, httpOptions).pipe(
      map((data: any[]) => [data].map((item) => this.adapter.adapt(item)))
    );
  }

}

product.model.ts

export class Product {
    constructor(
      public id: number,
      public productCode: string,
      public productName: string,
      public productPrice: number
    ) {}
  }

  @Injectable({
    providedIn: "root",
  })
  export class ProductAdapter implements Adapter<Product> {
    adapt(item: any): Product {
      return new Product(item.id, item.productCode, item.productName, item.productPrice);
    }
  }

更新 productList 价值观:

[Product]
0: Product
    id: undefined
    productCode: undefined
    productName: undefined
    productPrice: undefined
__proto__: Object
length: 1

Postman 的回应:

[
    {
        "id": 1,
        "productCode": "P01",
        "productName": "Pencil",
        "productPrice": 10.0
    }
],

输出:

Product List

Available Products
Product Name :
Product Code :
Product Price :

我做错了什么?

gkl3eglg

gkl3eglg1#

问题在于 [data].map((item) => this.adapter.adapt(item))) . 注意 data 已经是数组,因此不需要 [] .
试试这个:

data.map((item) => this.adapter.adapt(item)))

相关问题