html - Angular - TypeError:无法读取未定义的属性“名称”
问题描述
我不太确定如何以更好的方式表达这个问题,但我需要一些帮助来理解如何解决这个问题。以下是我的错误:
TypeError: _co.create is not a function
TypeError: Cannot read property 'name' of undefined
当我尝试newCategory.name
在 html 中使用时,它会在控制台中引发这些错误。所以我认为问题在于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
Category。
您可以通过以下方式初始化 newCategory:
- 使用
new
运算符
newCategory: Category = new Category();
- 我通常在类别模型文件中声明初始状态,然后将其导入适当的文件中。
export const initialState: Category = {
name: '',
description: ''
};
- 初始化组件中的值
newCategory: Category = {
name: '',
description: ''
};
推荐阅读
- r - 在购物篮分析中,我有什么办法只能在关联规则的 lhs 中获得 1 项?
- php - 如何一次抛出错误消息?
- java - 递归结构上的 DTO 投影
- angularjs - Angularjs Ng-init 在通过 ng-repeat 时显示相同的检索到的表单值
- db2 - DB2 锁定场景
- elasticsearch - 如何在 Elasticsearch 上索引混合语言内容?
- python-3.x - rasa nlu 多模型 python
- android - 无法使用 Webview android 获取 HTTP 401 错误的回调
- java - 仅通过引用对象来获取价值
- javascript - 用于 Alexa Lambda 的 NodeJS 中的 API 密钥