簡體   English   中英

ngFor 屬性“id”在“對象”類型上不存在

[英]ngFor Property 'id' does not exist on type 'Object'

我正在嘗試學習 angular 並且我正在遵循代碼教程,據我所知,我的代碼與講師匹配,但它不起作用。

我有以下代碼,它無法編譯說對象不存在。 我錯過了什么?

import { ThrowStmt } from '@angular/compiler';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

  products:Object[];

  constructor() {
    this.products = [
        {
          id: "1",
          name:"Mac Book Pro"
        },
        {
          id: "2",
          name:"iPhone"
        }
    ];
  }

  public getProducts(){
    return this.products;
  }


  ngOnInit(): void {
  }

}
Product Details:

<div *ngFor="let product of products">
    <h1>{{product.name}}</h1>
    <h1>{{product.id}}</h1>
</div>

如果我刪除.name和.id,它會打印兩次[[object Object]],但就目前而言,我得到以下錯誤。


4     <h1>{{product.name}}{{product.id}}</h1>
                    ~~~~

  src/app/product/product.component.ts:6:16
    6   templateUrl: './product.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component ProductComponent.


Error: src/app/product/product.component.html:4:35 - error TS2339: Property 'id' does not exist on type 'Object'.

4     <h1>{{product.name}}{{product.id}}</h1>
                                    ~~

解決我通過從 Object[] 更改為 any[] 解決了這個問題。

產品:任何[];

這解決了這個問題。

解決方案 1

您必須將products類型指定為具有強類型類/接口而不是Object[]的數組;

產品.model.ts

export interface Product {
  id: string;
  name: string;
}

product.component.ts

import { Product } from '../models/product.model';
products: Product[];

StackBlitz 上的示例解決方案 1


解決方案 2

或者,如果您更喜歡將products作為Object[]類型,請按如下方式更改文本插值。

<div *ngFor="let product of products">
  <h1>{{product["name"]}}</h1>
  <h1>{{product["id"]}}</h1>
</div>

StackBlitz 上的示例解決方案 2

嘗試使用? 運算符,如下所示:

<div *ngFor="let product of products">
    <h1>{{product?.name}}</h1>
    <h1>{{product?.id}}</h1>
</div>

如果任何產品缺少nameid屬性,您當前的代碼將中斷。

問題是使用類型 Object[] 交換到 any[] 解決了這個問題。

更改產品:Object[]; 到產品:任何[]; 即類型應該是any 而不是Object。 這是一個一般的 angular 錯誤。 希望他們解決。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM