有角度的范围问题

问题描述 投票:0回答:1

我有一个返回数组的服务。

main(){ 
    this.addressService.getState().subscribe( (data:any)=>{
          this.usStates = data;
          if(this.usStates.length===0) {
            this.notificationService.showErrorNotification('Unable to get states');
console.log(this.usStates); //length of array is 10
          }
        });
console.log(this.usStates); //empty array
}

如何在回调范围之外获取this.usStates的更新值?

angular typescript scoping
1个回答
0
投票

您的代码本身是正确的。这纯粹是一个时间问题。问题是订阅之外的第二个console.log(this.usStates);会立即执行 - 在这种情况下,this.usStates数组仍然是空的。基本上会发生以下情况:

enter image description here

因此,在subscribe函数之外,您只需要检查值是否存在。像这样的东西:

if (this.usStates.length>0) { console.log(...) }

或者,如果您绑定数据,则需要使用*ngIf或安全导航操作符(?)。

© www.soinside.com 2019 - 2024. All rights reserved.