我不太确定如何更好地表达这个问题,但我 需要一些帮助来了解如何解决这个问题。以下是我的错误:
类型错误:_co.create 不是函数
类型错误:无法读取未定义的属性“名称”
当我尝试在 html 中使用 newCategory.name
时,它会在控制台中抛出这些错误。所以我认为问题出在 HTML 上。
newCategory 在 CreateCategoryComponent.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:
- 使用
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/