0

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) {

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

    console.log("outside" + this.classes);
John Smith
  • 465
  • 1
  • 4
  • 18
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – deceze Oct 10 '16 at 07:25

2 Answers2

2

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.

Krenom
  • 1,894
  • 1
  • 13
  • 20
  • Thanks @Krenom, that makes sense. So how would I use that call to update my local calendar? I basically want to update the calendar when it is opened. Should I be using a different pattern from subscribe? – John Smith Oct 10 '16 at 08:31
  • @JohnSmith Check out my answer from the other day for this. Essentially you have a (shared) service that pushes the values out for the components to consume: http://stackoverflow.com/questions/39897670/how-can-i-create-a-variable-in-a-service-that-gets-its-data-from-a-promise-yet-i/39898499#39898499 – Krenom Oct 10 '16 at 09:01
1

How do I assign to my class variable

Inside the subscribe. The moment when the outside code executes the value hasn't come from the server. You cannot use a value from the future. So you must wait for it to come back and then use it.

basarat
  • 261,912
  • 58
  • 460
  • 511
  • Thanks @basarat, so is 'subscribe' the wrong pattern for my use case? When the class is initialised I want to update the calendar. Is that just a simple call to the server rather than subscribe? How would I achieve that? – John Smith Oct 10 '16 at 08:32
  • subscribe is the correct pattern. However you need to show a spinner (or some other indicator) till the results come back from the server. – basarat Oct 11 '16 at 04:39