John Smith John Smith - 1 year ago 69
TypeScript Question

Http Get - How to maintain state?

I'm a bit confused about angular Http Get observable. I want to assign the results of my observable to my class variable. If I log inside the subscribe, it prints the class variable OK. If I log outside of the subscribe, it shows an empty array. How do I assign to my class variable?

classes = [];

constructor(private navController:NavController, private httpService: HttpService) {

.subscribe((data) => {
this.classes = data;
console.log("inside" + this.classes);

console.log("outside" + this.classes);

Answer Source

To expand on @basarat's answer:

Http is asynchronous, it doesn't return a result immediately. I would expect the code you provided in your question to produce the console log "outside" before the "inside".

The code is sending off the call to the server (this.httpService.getCalendar...), and then continuing on, hitting the "outside" console.log.

x time later, the server is responding with your data. It is at this point that the subscribe section is hit asynchronously, and your classes is being filled (this.classes = data), and your "inside" console.log is finally shown.