首页 > 解决方案 > Angular:无法读取未定义的属性但仍显示数据

问题描述

我很困惑,因为我的应用程序正在显示必要的数据,但控制台中仍然存在我想摆脱的错误。

打字稿:

  activeClient: Client;

  constructor(private clientService: ClientService) { }

  ngOnInit() {
    this.inViewMode = true;
    this.clientId = parseInt(window.location.pathname.split('/')[2], 10);
    this.clientService.getClientById(this.clientId)
        .subscribe(data => this.activeClient = data);
  }

HTML:

<div class="form-row">
   <div class="form-group col-12">
       <label for="name">Ettevõtte nimi<span *ngIf="!inViewMode" class="required">*</span></label>
       <input class="form-control" id="name" [value]="activeClient.companyName">
   </div>
</div>

客户型号:

export interface Client {
    id?: number;
    companyName?: String;
    firmRegNo?: number;
    address?: String;
    clientName?: String;
    phoneOne?: number;
    phoneTwo?: number;
    email?: String;
    explanation?: String;
    rating?: number;
    status?: String;
    clientContract?: ClientContract;
}

标签: angular

解决方案


使用安全导航运算符来防止错误,直到activeClient被初始化:

[value]="activeClient?.companyName"

推荐阅读