首页 > 解决方案 > 错误类型错误:无法在 Object.eval [as updateRenderer] 处读取 null 的属性“电话”

问题描述

我有这个从 api 获取所有客户端的函数:

  this.ws.getallclients().subscribe(
  client => {
    this.client = client.map((clients) => {
      this.filteredOptions = this.addsale.controls['client_id'].valueChanges.pipe(
        startWith(''),
        map(val => this._filter(val))
      );
      return new Client(clients);
    });
    if (this.ss.getData('client_id')) {
      const client_id = this.ss.getData('client_id');
      this.addsale.controls.client_id.setValue(client_id)
      let selectedClient = new Client('')
      this.selectedClient = null;
      for (let i = 0; i < client.length; i++) {
        if (client[i].client_id === client_id) {
          this.selectedClient = client[i];
        }
      }
    }
  }
);

在此显示错误中:

错误类型错误:无法在 Object.eval [as updateRenderer] 处读取 null 的属性“电话”

因为 client[i].client_id 返回 client_id 像 123456 === 和 client_id 显示客户端的名称,如 MyName 和这个 html 代码:

我的html代码:

<fieldset>
<legend>Client Data</legend>
        <div class="input-field col s4">
        <input formControlName="client_id" id="client_id"   matInput placeholder="Select Client*" aria-label="State" [matAutocomplete]="auto" >
    <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" [displayWith]="displayFn">
      <mat-option (onSelectionChange)="onSelect(item.client_id)" *ngFor="let item of filteredOptions | async" [value]="item.name">
        {{item.name}}
      </mat-option>
    </mat-autocomplete>
</div>
   <div class="input-field col s12">
    ID Number:
     <span style="color:darkblue">{{selectedClient.phone}}</span>
     </div>
 </fieldset>

知道如何发出此错误吗?

标签: angulartypescript

解决方案


this.selectedClient = null如果没有选定的客户端,您的代码设置,然后您的模板尝试访问selectedClient.phone,导致错误。也许您打算替换这些行:

  let selectedClient = new Client('')
  this.selectedClient = null;

和:

  this.selectedClient = new Client('')

这样您Client在这种情况下就有一个空白对象。或者,ngIf如果没有selectedClient. 我不知道 Angular,但根据对文档的快速阅读,这可能有效:

<span *ngIf="selectedClient" style="color:darkblue">{{selectedClient.phone}}</span>

推荐阅读