[英]Angular - TypeError: Cannot read property 'name' of undefined
我不太確定如何以更好的方式表達這個問題,但我需要一些幫助來理解如何解決這個問題。 以下是我的錯誤:
TypeError: _co.create is not a function
TypeError: Cannot read property 'name' of undefined
當我嘗試在 html 中使用newCategory.name
時,它會在控制台中拋出這些錯誤。 所以我認為問題出在 HTML 中。
newCategory在CreateCategoryComponent.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:
new
運算符 newCategory: Category = new Category();
export const initialState: Category = {
name: '',
description: ''
};
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.