1

I'm new in Ionic world and I have some troubles when a function that I called in my Constructor. I'm making an app that makes room for university rooms. I've set up my web service and am making HTTP calls to get the answers back, but on some occasions, I need to save the values of those returns so I do not have to redo HTTP calls every time. But every time I try to access the values of these variables outside the promisse, they return undefined.

Here's what I'm doing and my question is: How do I assign the return values of the promise in my variables without losing the context of it.

export class MainPage{
  rooms: Array<Sala>; //array of rooms

  constructor(public navCtrl: NavController, public navParams: NavParams, public connection: ConnectionService) {
    this.callLoadRoom();
  }

  callLoadRoom() {
    var that = this;
    this.connection.loadRoom()
      .then( (data: Array<Sala>) => {
        that.rooms = data;
      }, (error) => {
        console.log("Load Rooms Error!", error);
      });
  }

  printRooms(){
    console.log(this.rooms)
  }
} 

The connection class is a provider that performs the HTTP call to the web service. Here's how I'm doing:

loadRoom() {
    return new Promise((resolve, reject) => {
      this.http.get(this.baseUri+'sala/carregarSala')
        .map(res => res.json())
        .subscribe(data => {
          resolve(data);
        },
        error => {
          reject(error);
        });
    });
  }

Thanks every one !

  • ***But every time I try to access the values of these variables outside the promisse, they return undefined.*** When are you trying to access this, I can see where, but is this a click event or when is `printRooms()` called? – AT82 Jul 25 '17 at 09:10
  • Let's assume that the printRooms() function is called after the callLoadRoom() function, I need the value that was assigned in the ROOMS vector to be available to perform other operations with it. Can you help me with this? – Gabriel Schiavon Aug 28 '17 at 21:28
  • I perhaps would then see this as a duplicate of this: https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2 It's the asynchronous nature, you cannot be sure that the value is there in any other way than to properly chain this. There are some rxjs functions that could help with this, but since not knowing the exact use case (when/how `printRooms()` is called) So without the exact usecase, this is the best I can offer :) – AT82 Aug 29 '17 at 17:46

1 Answers1

1

Don't use var that = this it is not necessary, use this directly.

Your loadRoom() method can be cleaned up like:

loadRoom() {
  return this.http.get(this.baseUri+'sala/carregarSala')
    .map(res => res.json())
    .toPromise()
    .catch(err => {
       // handle error here
    }
}

More information on .toPromise() in this question

You can see a live plunker demo here

0mpurdy
  • 3,198
  • 1
  • 19
  • 28