Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dismiss Loader after data is ready

In my Ionic 2 app, I have a component that consumes a service which makes an http GET to fetch some data. My component then calls this service and when data is available it sets and presents it.

It looks like following:

export class FarmList implements OnInit {

  items: Object;


  constructor(public testService: TestService, public nav: NavController){
  }

  ngOnInit(){

    this.getData()
  }

  getData(){

    let loading = Loading.create({
      content: 'Please wait..',
      spinner: 'crescent'
    })

    this.nav.present(loading)

    this.testService.fetchData().then(data => this.items = data)

  }
...

}

While my component fetches the data asynchronously, I am trying to have a loader spinning and once the data is available, I want the loader to disappear.

However, with my current code the spinner keeps spinning even after data is available and displayed as can be seen the screenshot:

enter image description here

getData() is the method that makes service call. How can I fix this? Is it the correct way to implement loader?

like image 974
Thinker Avatar asked Jun 29 '16 09:06

Thinker


1 Answers

You can find a working plunker here.

Like you can see in the code of that plunker, I would make a few changes in order to make your code work properly:

  export class FarmList implements OnInit {

  items: Object;

  // Define the loading var here, so we can access later when the information is ready
  loading : any;

  constructor(public testService: TestService, public nav: NavController){
  }

  // Instead of 'ngOnInit', I would use 'ionViewWillEnter'
  ionViewWillEnter(){
    this.getData()
  }

  getData(){

    this.loading = Loading.create({
      content: 'Please wait..',
      spinner: 'crescent'
    })

    this.nav.present(this.loading)

    this.testService.fetchData().then(data => { 
                                       this.items = data;

                                       // After we get the data, we hide the loading
                                       this.hideLoading()});

  }

  // I 've added this method so we can grab the loading var and use it 
  // to hide the loading component.
  private hideLoading(){
    this.loading.dismiss();
  }
...

}

================================

UPDATE:

As of the release of Ionic 2.0.0-beta.8 (2016-06-06) changelog:

onPageWillEnter was renamed to ionViewWillEnter

like image 149
sebaferreras Avatar answered Oct 15 '22 21:10

sebaferreras