【问题标题】:Why do I get Type error: Object is possibly 'null'?为什么会出现类型错误:对象可能为“空”?
【发布时间】: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


【解决方案1】:

你的编辑是对的,我也相信这个对象可以为空。为什么?因为这条线:

currentClient = null;

从外部的角度来看,我可以随时调用delete函数,这意味着你的currentClient变量可以为null,因为你初始化它!

有两个主要选项可以解决这个问题:

仅当您知道一旦退出类的构造函数后您的变量将永远不会是 null or undefined 时,才应使用第二种解决方案。

您可能还想看看可空运算符。 private currentClient?: Client;

【讨论】:

  • 谢谢,我试过检查值,但没有用,我得到了同样的错误
猜你喜欢
  • 2021-06-07
  • 2016-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-04
相关资源
最近更新 更多