-1

I am working with angular and typescript and want to change the value of the variable inside the function. I am using a service to get the data. The code is shown below:

 isValue:boolean = false;

  onChangeValue(list: List) {
     this.someServive.getData(list).subscribe(
        item => {
        if(item.value === 1) {
            this.isValue = true;
          }
       }); 
   console.log(this.isValue);          //the value is still false here  
  }
Laxmee
  • 47
  • 1
  • 6

2 Answers2

0

Good day!

It happens due to the fact, that your service call is an async operation. And browser doesn't wait when your service emits some value, which you handle in subscription block.

  isValue = false;

  onChangeValue(list: List) {
     this.someServive.getData(list).subscribe(item => {
       if (item.value === 1) {
         this.isValue = true;
         this.executeOnUpdateCallback();
       }
     });   
  }

  executeOnUpdateCallback() {
     console.log(this.isValue); // true  
  }

Something like this you should do to handle it. I hope, you got it (please google about js event loop)

AlexanderFSP
  • 652
  • 4
  • 10
  • Thanks @AlexanderFSP . I am quite not sure how the above solution will help in my context. Just to clarify you, isValue property is used in my templete inside `div *ngIf = "isValue"` and whenever the data from the service comes in and is equal to 1, the div should be displayed. How can I use the above in that context? – Laxmee Apr 01 '20 at 10:08
  • @Laxmee, I suppose your logic should works now without any changes. When data from the service comes - you make isValue to equal true - change detection mechanism triggers (do some checks) and rerender your component, so this div becomes visible. – AlexanderFSP Apr 01 '20 at 10:14
  • Of course, it won't be work if you use `ChangeDetectionStrategy.OnPush` – AlexanderFSP Apr 01 '20 at 10:16
0

Since javascript is asynchronous, the value won't change until the getData service call actually happens.

In your case console executes before the getData happens.

You can either try it with promise or callback

Try below:

isValue:boolean = false;

onChangeValue(list: List) { 
   onDataRecieved((res)=>{
     console.log(this.isValue);
   });    
}       

onDataRecieved(cb){
 this.someServive.getData(list).subscribe(
      item => {
      if(item.value === 1) {
         this.isValue = true;
         cb(true);
      }
   });
}
dECRISES
  • 1
  • 1