>我有这个函数,可以从 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]
因为客户端[i].client_id返回client_id,如123456===client_id显示客户端名称,如MyName 和这个 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>
知道如何发出此错误吗?
如果没有选定的客户端,则代码设置this.selectedClient = null
,然后模板尝试访问selectedClient.phone
,从而导致错误。 也许您打算替换这些行:
let selectedClient = new Client('')
this.selectedClient = null;
跟:
this.selectedClient = new Client('')
以便在这种情况下有一个空白Client
对象。 或者,如果没有selectedClient
,您可能想使用ngIf
来避免评估模板中存在问题的部分。 我不了解 Angular,但根据对文档的快速阅读,这可能会起作用:
<span *ngIf="selectedClient" style="color:darkblue">{{selectedClient.phone}}</span>