我很困惑,因为我的应用程序是显示必要的数据,但仍有在控制台的错误,我想摆脱。
打字稿:
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;
}
使用safe navigation operator防止错误,直到activeClient
初始化:
[value]="activeClient?.companyName"
由模板被渲染的时候,activeClient
不存在(等待可观察到拉数据)。使用elvis运营安全显示。
[value]="activeClient?.companyName"
你通过进行activeClient
调用的API获得了async
值。您的模板不会等待那个被定义的,直到现在。因此你要在控制台上的错误。
只要activeClient
在subscribe
块初始化,你看到的价值。
为了避免这种情况,直到activeClient
初始化不呈现模板。
由于activeClient
有很多领域,我推荐使用*ngIf
:
<div class="form-row" *ngIf="activeClient">
<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>
async
管:activeClient$: Observable<Client>;
constructor(private clientService: ClientService) {}
ngOnInit() {
this.inViewMode = true;
this.clientId = parseInt(window.location.pathname.split('/')[2], 10);
this.activeClient$ = this.clientService.getClientById(this.clientId);
}
而在你的模板:
<div class="form-row" *ngIf="activeClient$ | async as activeClient">
<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>