How to dismiss Loader after data is ready
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
Thinker
Updated on July 23, 2022Comments
-
Thinker almost 2 years
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 theloader
to disappear.However, with my current code the spinner keeps spinning even after data is available and displayed as can be seen the screenshot:
getData()
is the method that makes service call. How can I fix this? Is it the correct way to implement loader? -
Thinker almost 8 yearsIt fails to load the data saying: Error: Uncaught (in promise): [object Object](…) and console.log(this.items) in the getData() at the end prints undefined
-
sebaferreras almost 8 yearsGlad to be helpful :) Did you find any error in the code I posted above? If so, please feel free to edit it or just tell me and I'll update the answer.
-
Thinker almost 8 yearsI just used ngOnInit instead of ionViewWillEnter. I would like if you point out why ionViewWillEnter you prefer?
-
sebaferreras almost 8 yearsIt's not something I personally prefer, it's just the way that Ionic Team recommends to do things, just like you can see in the changelog
-
Abhay over 5 yearspresent does not exist on type 'NavController'
-
Kamlesh about 5 yearshow can we do the same in ionic4? Kindly suggest. Thanks.