Angular 即使绑定正在工作,也无法读取未定义错误的属性
因此,我在我的web应用程序中有一个下拉列表,我连接到我的服务api调用,该调用将用位置列表填充下拉列表 我创建了服务,并使用httpclient设置了Observable 然后我调用服务来获取api调用的结果,并绑定到我的location属性 例如,在Angular 即使绑定正在工作,也无法读取未定义错误的属性,angular,typescript,ngoninit,Angular,Typescript,Ngoninit,因此,我在我的web应用程序中有一个下拉列表,我连接到我的服务api调用,该调用将用位置列表填充下拉列表 我创建了服务,并使用httpclient设置了Observable 然后我调用服务来获取api调用的结果,并绑定到我的location属性 例如,在ngOnInit()内的我的component.ts文件中,我有: ngOnInit() { this._transactionService.getLocations('User').subscribe(data => this.
ngOnInit()
内的我的component.ts文件中,我有:
ngOnInit() {
this._transactionService.getLocations('User').subscribe(data => this.location = data);
}
在my component.html文件中:
<select [ngModel]="null" formControlName="location">
<option value="null" disabled selected>{{'SelectLocation' | translate}}</option>
<option *ngFor="let store of location._storeList" [ngValue]="store._storeKey">{{ store._storeName }}</option>
</select>
因此,虽然绑定和结果工作正常,但我不确定为什么会出现控制台错误。我认为这与
ngOnInit()
的角度生命周期有关,但我不确定如何正确解决这个问题。我应该调用我的服务而不是ngOnInit()
或其他地方吗?解决此问题的最佳做法是什么 因为位置
是异步加载的,所以在第一次执行模板时,它是未定义的
解决方案是使用(又名elvis?。
)运算符:
<option *ngFor="let store of location?._storeList" [ngValue]="store._storeKey">{{ store._storeName }}</option>
{{store.\u storeName}
<option *ngFor="let store of location?._storeList" [ngValue]="store._storeKey">{{ store._storeName }}</option>