【发布时间】:2021-07-05 05:32:36
【问题描述】:
在我的 Angular 项目中,我想实现删除项目,但是当我使用 this.currentClient.id 或 .this.currentClient.name 时出现此错误:
类型错误:对象可能是“空”
这是一个带有更新 currentClient 数据和删除功能的片段:
export class ClientDetailsComponent implements OnInit {
currentClient = null;
message = '';
getClient(id: string | null): void {
this.clientService.get(id)
.subscribe(
data => {
this.currentClient = data;
console.log(data);
},
error => {
console.log(error);
});
}
deleteClient(): void {
this.clientService.delete(this.currentClient.id)
.subscribe(
response => {
console.log(response);
this.router.navigate(['/clients']);
},
error => {
console.log(error);
});
}
我不知道为什么它可以为空:(
【问题讨论】:
-
因为你用空值初始化它?
currentClient = null。在访问子属性之前执行空值检查,或者使用可选链接,即this.currentClient?.id
标签: angular typescript