簡體   English   中英

Angular - 類型錯誤:無法讀取未定義的屬性“名稱”

[英]Angular - TypeError: Cannot read property 'name' of undefined

我不太確定如何以更好的方式表達這個問題,但我需要一些幫助來理解如何解決這個問題。 以下是我的錯誤:

  1. TypeError: _co.create is not a function
  2. TypeError: Cannot read property 'name' of undefined

當我嘗試在 html 中使用newCategory.name時,它會在控制台中拋出這些錯誤。 所以我認為問題出在 HTML 中。

newCategoryCreateCategoryComponent.ts中定義

newCategory: Category;
name: string;
description: string;

分類服務.ts

 //ommitted some redundant code
 baseUrl: string = "api/Category";

 createCategory(newCategory: Category) : Observable<any> {

  //Not too sure if newCategory is added correctly here
  return this.httpClient.get<any>(this.baseUrl+"username="+this.sessionService.getUsername()+"&password="+this.sessionService.getPassword() + newCategory).pipe (
    catchError(this.handleError)
    );
  }

創建類別.html

<td><input id="name" name="name" #name="ngModel" type="text" [(ngModel)]="newCategory.name" required="true" /></td>

您的 HTML 沒有任何問題。

問題是newCategory: Category; 因為值沒有被初始化。 您在這里所做的只是將 newCategory 設置type of類別類型。

您可以通過以下方式初始化 newCategory:

  1. 使用new運算符
       newCategory: Category = new Category();
  1. 我通常在類別模型文件中聲明初始狀態,然后將其導入適當的文件。
    export const initialState: Category = {
      name: '',
      description: ''
    };
  1. 初始化組件中的值
    newCategory: Category = {
      name: '',
      description: ''
    };

您的組件有 3 個屬性:

  • 新類別:類別;
  • 名稱:字符串;
  • 描述:字符串;

然后您需要設置/獲取屬性名稱,您將使用: name

<td><input id="name" name="name" #name="ngModel" type="text" [(ngModel)]="name" required="true" /></td>

或者您需要將name添加到您的newCategory對象:

newCategory: Category = {
    name: string, 
    description: string
};

並在模板中使用newCategory.name

<td><input id="name" name="name" #name="ngModel" type="text" [(ngModel)]="newCategory.name" required="true" /></td>

希望這有幫助!

這發生在我從異步調用返回對象之前加載頁面時。 我的解決方案是 *ngIf 塊。

<div *ngIf="object"><br />
<b>{{ object.property1}}</b><br />
<i>{{ object.property2}}</i><br />
</div>

暫無
暫無

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

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