Ionic 2 - Loading Controller doesn't work

丶灬走出姿态 提交于 2019-12-05 03:29:52

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

  }
}

I put "loading.dismiss();" in subscribe {} and it works well :)

                    this.http.get(url)
                        .subscribe(data =>{
                            this.items=JSON.parse(data['_body']).results;
                            loading.dismiss();
                        },

You can use the ionic ionViewLoaded() to pop up the Loading Controller and then Dismiss it when the View is loaded and the Content Fetched from your Subscribtion.

ionViewLoaded() {
  let lr = this.loading.create({
    content: 'Your Display Message...',
  });

  lr.present().then(() => {
    this.Yourservice.Yourfunction()
      .subscribe(res => {
        this.yourresult = res;
      });
    lr.dismiss();
  });
}

You can also structure your code like this to make sure the Subscription is Complete before you Dismiss the Loader.

ionViewLoaded() {
      let lr = this.loading.create({
        content: 'Your Display Message...',
      });

      lr.present().then(() => {
        this.Yourservice.Yourfunction()
          .subscribe(
          data => this.yourresult = data,
          error => console.log(error),
          ()=> lr.dismiss()
          );

      });
    }

For the last versione of ionic you ve to handle the dismiss event:

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

loading.present();

loading.onDidDismiss().then(() => {
     do thinks..... 
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!