Gabriel Schiavon
Gabriel Schiavon

Reputation: 11

Assign a return value of promise to the variable always undefined ionic2

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 !

Upvotes: 1

Views: 900

Answers (1)

0mpurdy
0mpurdy

Reputation: 3353

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

Upvotes: 1

Related Questions