所以,我的Web应用程序中有一个下拉列表,我将其连接到我的服务API调用中,该呼叫将填充下拉菜单中的位置列表。
我创建了服务,并使用HTTPClient设置可观察的。
然后,我致电该服务以获取API调用的结果并绑定到我的位置属性。
例如。在ngOnInit()
内部的component.ts文件中,我有一个:
ngOnInit() {
this._transactionService.getLocations('User').subscribe(data => this.location = data);
}
在我的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>
当我加载页面时,我会简要注意到,它会像SEC的一小部分一样加载怪异,然后纠正自身并正确加载。我检查下拉菜单,并看到它正确地绑定了所需的位置列表,并且可以选择它。看起来不错!但是,当我检查元素>控制台时,我会看到此错误:
ERROR TypeError: Cannot read property '_storeList' of undefined
at Object.eval [as updateDirectives] (PortalComponent.html:11)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:14651)
at checkAndUpdateView (core.js:13798)
at callViewAction (core.js:14149)
at execComponentViewsAction (core.js:14081)
at checkAndUpdateView (core.js:13804)
at callViewAction (core.js:14149)
at execEmbeddedViewsAction (core.js:14107)
at checkAndUpdateView (core.js:13799)
at callViewAction (core.js:14149)
因此,虽然绑定和结果效果很好,但我不确定为什么要遇到控制台错误。我认为这与ngOnInit()
的角生命周期有关,但我不确定如何正确解决此问题。我应该打电话给我的服务,而不是ngOnInit()
或其他地方吗?解决此问题的最佳实践是什么?
因为 location
是异步加载的,使用,首次是 undefined
,在Angular Loads执行模板。
解决方案是使用安全导航(aka elvis ?.
(操作员:
<option *ngFor="let store of location?._storeList" [ngValue]="store._storeKey">{{ store._storeName }}</option>