即使绑定正在工作,也无法读取未定义错误的属性

时间:2018-03-26 22:09:02

标签: angular typescript ngoninit

所以,我在我的网络应用程序中有一个下拉菜单,我连接到我的服务api调用,它将填充下拉列表中的位置列表。

我创建了服务并使用httpclient设置了Observable。

然后我调用该服务来获取api调用的结果并绑定到我的location属性。

E.g。在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>

当我加载页面时,我会短暂地注意到,它会像一秒钟一样加载怪异,然后自行纠正并正确加载。我查看我的下拉菜单,我看到它正确绑定了我想要的位置列表,我可以选择它就好了。看起来不错!但是,当我检查元素&gt;控制台,我看到了这个错误:

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()的Angular生命周期有关,但我不确定如何正确解决这个问题。我应该拨打我的服务而不是ngOnInit()或其他地方吗?解决此问题的最佳做法是什么?

1 个答案:

答案 0 :(得分:1)

因为location是异步加载的,所以在Angular加载第一次执行模板时,使用它是undefined

解决方案是使用Safe Navigation(aka elvis ?.)运算符:

<option *ngFor="let store of location?._storeList" [ngValue]="store._storeKey">{{ store._storeName }}</option>