Thomas Dussaut Thomas Dussaut - 3 months ago 138
TypeScript Question

Ionic 2 - Loading Controller doesn't work

I am trying to use the recently added LoadingController this way :

let loading=this.load.create({
content: "Connexion au serveur Migal en cours..."
});

loading.present();

this.http.get(this.urlCheckerForm.value.migalUrl+'/action/MobileApp/URLChecker')
.map(res => res.json())
.subscribe(
data => this.newConnection(data,loading),
error => this.catchURLError(loading));

loading.dismiss();


Basically, I just want to display my loading pop-in before my page is loaded, and dismiss it after.

I followed the example on Ionic 2 Documentation, but it doesn't seem to work at all...

EDIT : The loading component doesn't even show up.

Answer

The issue with your code is that you're making the http request and then calling the dismiss() but the dismiss() method does not wait for the http request to finish. Please take a look at this plunker.

The code is pretty much self-explanatory:

import { NavController, LoadingController } from 'ionic-angular/index';
import { Http, Response } from '@angular/http';
import { Component } from "@angular/core";
import 'rxjs/Rx';

@Component({
  templateUrl:"home.html"
})
export class HomePage {

  private users : Array<any>

  constructor(private http: Http, private loadingCtrl: LoadingController) {

    // Create the popup
    let loadingPopup = this.loadingCtrl.create({
      content: 'Loading data...'
    });

    // Show the popup
    loadingPopup.present();

    // Get the data
    this.http.get('https://jsonplaceholder.typicode.com/users')
      .map((res: Response) => res.json())
      .subscribe(
        data => {

          // I've added this timeout just to show the loading popup more time
          setTimeout(() => {
            this.users= data;
            loadingPopup.dismiss();
          }, 1000);

          // Should be just this:
          // this.users= data;
          // loadingPopup.dismiss();
        },
        err => console.error(err)
    );

  }
}
Comments