首页 > 解决方案 > Angular - TypeError:无法读取未定义的属性“名称”

问题描述

我不太确定如何以更好的方式表达这个问题,但我需要一些帮助来理解如何解决这个问题。以下是我的错误:

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

当我尝试newCategory.name在 html 中使用时,它会在控制台中引发这些错误。所以我认为问题在于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>

标签: htmlangulartypescript

解决方案


您的 HTML 没有任何问题。

问题在于newCategory: Category;未初始化值。您在这里所做的只是将 newCategory 设置为type ofCategory。

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

  1. 使用new运算符
       newCategory: Category = new Category();
  1. 我通常在类别模型文件中声明初始状态,然后将其导入适当的文件中。
    export const initialState: Category = {
      name: '',
      description: ''
    };
  1. 初始化组件中的值
    newCategory: Category = {
      name: '',
      description: ''
    };

推荐阅读