【问题标题】:Angular - TypeError: Cannot read property 'name' of undefinedAngular - TypeError:无法读取未定义的属性“名称”
【发布时间】:2019-09-06 16:40:39
【问题描述】:

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

  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;

CategoryService.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)
    );
  }

CreateCategory.html

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

【问题讨论】:

  • newCategory: Category; 这仅将 newCategory 定义为 Category 类型,但不会初始化值
  • newCategory 在您的组件中声明,但未定义
  • @mxr7350 是的。我错过了。谢谢你。需要添加 this.newCategory = new Category();

标签: html angular typescript


【解决方案1】:

您的 HTML 没有任何问题。

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

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

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

【讨论】:

    【解决方案2】:

    你的组件有 3 个属性:

    • newCategory:类别;
    • 名称:字符串;
    • 描述:字符串;

    然后您需要设置/获取属性名称,您将使用: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>
    

    希望对您有所帮助!

    【讨论】:

      【解决方案3】:

      在从异步调用返回对象之前加载页面时,我发生了这种情况。我的解决方案是 *ngIf 块。

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

      【讨论】:

        猜你喜欢
        • 2021-08-16
        • 2021-11-13
        • 2022-01-14
        • 2022-06-22
        • 2015-10-16
        • 2021-12-28
        • 2020-10-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多