enfix
enfix

Reputation: 6970

Loading controller await problem with Ionic

In my ngOnInit page I call a function to present a Loading and then call my service to load data. The problem is that the service call ends before the loading starts. How is it possibile with await?

loading: any;
...
ngOnInit() { 
    this.presentLoading();
    this.myService.get().subscribe((item)=>{
      console.log('dismiss');
      this.loading.dismiss();
    }, ()=>{
      this.loading.dismiss();
    })
  }

  async presentLoading() {
    this.loading = await this.loadingController.create({
      message: 'Loading...',
      duration: 20000
    });
    console.log('presentLoading')
    await this.loading.present();
  }

In console i can see:

dismiss
ERROR TypeError: Cannot read property 'dismiss' of undefined....
presentLoading

I’m using Ionic4.

Upvotes: 0

Views: 542

Answers (1)

Sergey Rudenko
Sergey Rudenko

Reputation: 9227

In your case (based on the code) you have presentLoading function that returns a promise (async), so even though inside of it you are using await statements - inside the ngOnInit hook nothing instructs execution to await for the presentLoading.

You could do:

  async ngOnInit() { 
    await this.presentLoading();
    this.myService.get().subscribe((item)=>{
      console.log('dismiss');
      this.loading.dismiss();
    }, ()=>{
      this.loading.dismiss();
    })
  }

Also since you are using Onservables it may makes sense to call dismiss inside "completed" function:

  async ngOnInit() { 
    await this.presentLoading();
    this.myService.get().subscribe((item)=>{
      console.log('dismiss');
    }, (error)=>{
      console.log(error);
    }, (completed)=>{
      this.loading.dismiss();
    }
  })

A note - making ngOnInit an async method does not "hurt", but its best to know a bit more waht implications it has: async/await in Angular `ngOnInit`

Upvotes: 1

Related Questions