Search code examples
angulartypescriptscoping

scoping issues in angular


I have a service that returns an array.

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
}

How can I get the updated value of this.usStates outside the scope of callback?


Solution

  • Your code is by itself correct. This is purely a timing issue. The problem is that the second console.log(this.usStates); which is outside of the subscription is executed immediately - and in that case the this.usStates array is still empty. Basically the following is happening:

    enter image description here

    So outside of the subscribe function, you just need to check for the existence of the value. Something like this:

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

    Or if you are binding to the data, you need to use *ngIf or the safe navigation operator (?).