簡體   English   中英

core.js:5980 錯誤類型錯誤:無法讀取未定義的屬性“名稱”(角度)

[英]core.js:5980 ERROR TypeError: Cannot read property 'Name' of undefined (angular)

我無法生成帶有 angular 信息的卡片

我的 model:

export class order {
    Name!: string
    Surname!: string
    Email!: string
    Type!: string
    Description!: string

    constructor(name: string, surname: string, email: string, type: string, desc: string) {
        this.Name = name,
            this.Surname = surname,
            this.Email = email,
            this.Type = type,
            this.Description = desc
    }
}

卡組件 typescript:

import { Component, Input, OnInit } from '@angular/core';
import { order } from 'src/app/shared models/order.model';

@Component({
  selector: 'app-contact-card',
  templateUrl: './contact-card.component.html',
  styleUrls: ['./contact-card.component.css']
})
export class ContactCardComponent implements OnInit {
  @Input()
  item!: order;
  constructor() { }

  ngOnInit(): void {
  }

}

卡組件 html:

<div class="card">
    <h3>{{item.Name}} {{item.Surname}}</h3>
    <div class="flex">
        <p>{{item.Email}}</p>
        <p>{{item.Type}}</p>
    </div>
    <p>{{item.Description}}</p>
</div>

它說當我插入字符串時錯誤出現在我的 html 上

是否需要使用 class 進行order 類需要被實例化。 如果它不包含方法並且沒有明確的需要,我建議您改用 TS接口 它允許在沒有 class 附帶的“膨脹”的情況下進行類型檢查。

export interface order {
    Name!: string;
    Surname!: string;
    Email!: string;
    Type!: string;
    Description!: string;
}

然后,您可以使用安全導航運算符?. 在 Angular 模板中,以避免潛在的undefined錯誤。 在嘗試訪問其屬性之前,它會檢查 object 是否已定義。

<div class="card">
    <h3>{{item?.Name}} {{item?.Surname}}</h3>
    <div class="flex">
        <p>{{item?.Email}}</p>
        <p>{{item?.Type}}</p>
    </div>
    <p>{{item?.Description}}</p>
</div>

請檢查item的值。 可能是nullundefined ,這就是發生此錯誤的原因。 為避免此錯誤,請嘗試以下操作:

<div class="card">
    <h3>{{item?.Name}} {{item?.Surname}}</h3>
    <div class="flex">
        <p>{{item?.Email}}</p>
        <p>{{item?.Type}}</p>
    </div>
    <p>{{item?.Description}}</p>
</div>

閱讀安全導航運算符 (?.) 或 (..) 和 null 屬性路徑了解更多詳細信息。

暫無
暫無

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

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