Html 角度-类型错误:无法读取属性';名称';未定义的
我不太确定如何更好地表达这个问题,但我 需要一些帮助来理解如何解决这个问题。以下是我的错误:Html 角度-类型错误:无法读取属性';名称';未定义的,html,angular,typescript,Html,Angular,Typescript,我不太确定如何更好地表达这个问题,但我 需要一些帮助来理解如何解决这个问题。以下是我的错误: TypeError:\u co.create不是一个函数 TypeError:无法读取未定义的属性“name” 当我尝试在html中使用newCategory.name时,它会在控制台中抛出这些错误。所以我认为问题在于HTML CreateCategoryComponent.ts中定义了newCategory newCategory: Category; name: string; descriptio
TypeError:\u co.create不是一个函数
TypeError:无法读取未定义的属性“name”
newCategory.name
时,它会在控制台中抛出这些错误。所以我认为问题在于HTML
CreateCategoryComponent.ts中定义了newCategory
newCategory: Category;
name: string;
description: string;
//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)
);
}
CategoryService.ts
newCategory: Category;
name: string;
description: string;
//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)
);
}
//输入了一些冗余代码
baseUrl:string=“api/Category”;
createCategory(newCategory:Category):可观察{
//不太确定此处是否正确添加了newCategory
返回this.httpClient.get(this.baseUrl+“username=“+this.sessionService.getUsername()+”&password=“+this.sessionService.getPassword()+newCategory).管道(
catchError(this.handleError)
);
}
CreateCategory.html
<td><input id="name" name="name" #name="ngModel" type="text" [(ngModel)]="newCategory.name" required="true" /></td>
您的组件有3个属性:
- 新类别:类别李>
- 名称:字符串李>
- 描述:字符串李>
name
或者您需要将name
添加到newCategory
对象:
newCategory:Category={
名称:string,
描述:字符串
};
并在模板中使用newCategory.name
:
希望这有帮助 您的HTML没有问题
问题是
newCategory:Category代码>因为值未初始化。您在这里所做的就是将newCategory设置为类别的类型
您可以通过以下方式初始化newCategory:
使用new
运算符
我通常在类别模型文件中声明初始状态,然后将其导入适当的文件中
初始化组件中的值
我在从异步调用返回对象之前加载页面时发生了这种情况。我的解决方案是一个ngIf块
<div *ngIf="object"><br />
<b>{{ object.property1}}</b><br />
<i>{{ object.property2}}</i><br />
</div>
{{object.property1}}
{{object.property2}}
新建类别:类别代码>这只将newCategory定义为类别的类型,但它不会初始化值newCategory
在组件内部声明,但不会初始化defined@mxr7350对我错过了。非常感谢。需要添加此项。newCategory=新类别();
<div *ngIf="object"><br />
<b>{{ object.property1}}</b><br />
<i>{{ object.property2}}</i><br />
</div>