html - Angular - 类型错误 : Cannot read property 'name' of undefined

标签 html angular typescript

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

  1. 类型错误:_co.create 不是函数
  2. 类型错误:无法读取未定义的属性“名称”

当我尝试在 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>

最佳答案

您的 HTML 没有任何问题。

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

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

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

    关于html - Angular - 类型错误 : Cannot read property 'name' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55710516/

    相关文章:

    css - 我们可以将默认的 Angular 形 Material 芯片设计更改为矩形吗?

    html - 图内 img 和 figcaption 之间不需要的空格

    angular - HttpInterceptors 处理 http 错误 Angular 4.3

    angular - 如何使用http拦截器以 Angular 获取响应 header

    angular - 限制在 agm-map 中的特定国家/地区

    typescript - 为什么长度应该是索引器的子类型?

    html - css 不同高度 div 网格空间

    javascript - Count++ 和 -- 不起作用

    html - "Overflow-scroll true"不适用于 ios 设备的 ionic 应用程序

    javascript - formArray 循环不完整的值