angular 中的范围界定问题

scoping issues in angular

我有一个 returns 数组的服务。

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 的更新值?

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

所以在订阅函数之外,您只需要检查值是否存在。像这样:

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

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