错误TypeError:无法在Object.eval读取为null的属性“ phone” [作为updateRenderer]

时间:2018-10-23 11:02:16

标签: angular typescript

我具有从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];
        }
      }
    }
  }
);

在此显示错误中:

  

错误TypeError:无法读取位于以下位置的null属性“ phone”   Object.eval [作为updateRenderer]

因为client [i] .client_id返回像123456 ===这样的client_id,而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>

您知道如何发出此错误吗?

1 个答案:

答案 0 :(得分:0)

如果没有选定的客户端,则您的代码将设置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>