【问题标题】:Cannot read property of undefined error even though the binding is working即使绑定正在工作,也无法读取未定义错误的属性
【发布时间】:2023-03-10 22:54:01
【问题描述】:

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

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

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

例如在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>

当我加载页面时,我注意到它在几分之一秒内奇怪地加载,然后自行纠正并正确加载。我检查了我的下拉列表,发现它正确地绑定了我想要的位置列表,我可以很好地选择它。看起来不错!但是,当我检查元素 > 控制台时,我看到了这个错误:

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() 或其他地方吗?解决此问题的最佳做法是什么?

【问题讨论】:

    标签: angular typescript ngoninit


    【解决方案1】:

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

    解决方案是使用Safe Navigation(又名猫王?.)运算符:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-05
      • 2017-11-10
      • 2016-05-26
      • 2018-10-30
      • 2022-10-07
      • 1970-01-01
      • 2022-06-16
      相关资源
      最近更新 更多