0

First of all, sorry for this presentation, It is not on the same computer.

I am trying to hide/show a panel using a boolean attribute in angular. I got : public existsLegend: any = {}; and public isLegendPanelActive: boolean = false;

I coded a method getLegend(url): Observable<Blob> which uses http.get from httpClientModule. Then, I subscribed to this method to see the result/error. At this moment, i got :

this.getLegend(legendURL).subscribe((data) => {...}, (error) => {...}, () => {...})

in the success i do : this.existLegends[layer.layer.layerId] = true

in the error i do : this.existLegends[layer.layer.layerId] = false

And in Complete :

let toShow = false;
for(const key in existLegends){
  if(this.existLegends[key] == true){
    toShow = true;
    break;
  }
}
this.isPanelLegendActive = toShow;
console.log(this.isLegendPanelActive) // return true or false as needed

but If I put the same console.log outside the subscribe function I got console.log(this.isLegendPanelActive) // return undefined

I tried a lot of things to see if the value was undefined due to async subscribe. But it not seems to be that. In fact I used a setInterval to print each second the value of my var and it is still undefined. even at the first instance instead of false as initialization.

Please if someone has an idea and could help me. Thank you

Fab83i
  • 85
  • 7
  • observable is asyncronous, meaning, whatever is in the subscribe will execute later, after all the syncronous code is executed. this [link](http://latentflip.com/loupe/) will help you – Naren Murali Oct 14 '21 at 12:04
  • I used a setInterval loop to see if the data will come later, but it does not. I guess that even if the async code is executed later, it will change my value – Fab83i Oct 14 '21 at 12:12
  • No ? I understand that it is executate later, but it should arrive later, shouldn't ? – Fab83i Oct 14 '21 at 15:15
  • Ok, I got your point. Could you please try swapping the normal functions to arrow functions so that scope variable are updated properly, just a possible suggestion, may not work out. – Naren Murali Oct 14 '21 at 15:49
  • There is a difference in naming: `isLegendPanelActive` vs `isPanelLegendActive`. Initially you set `public isLegendPanelActive: boolean = false;` so `console.log(this.isPanelLegendActive)` will be undefined. – Steve Holgado Oct 14 '21 at 20:17
  • @SteveHolgado my bad, it's the same naming for both, just made mistake writting this post – Fab83i Oct 15 '21 at 06:43
  • I've encountered a similar problem before and it was related to javascript context. Where are you subscribing and where are you trying to console.log isPanelLegendActive? Can you update more of your code in the question. – O.MeeKoh Oct 17 '21 at 16:20

0 Answers0