Toast message does not show up when I call it from app.components.ts

541 Views Asked by At

I'm trying to display toast message when the app receives FCM push notifications while the app in foreground but the toast message does not show up, I placed alert(data.message) and the alert show up without issue but toast messages does not. BTW the toast message works fine in other pages in the app but not in app.components.ts

initializeApp() {
  this.platform.ready().then(() => {

     this.fcm.onNotification().subscribe(data => {
       console.log(data);
       if (data.wasTapped) 
       {
        ....
        ...
       } else {
         alert(data.message);

         this.presentToast(data.message);
       }
      });      

      // refresh the FCM token
      this.fcm.onTokenRefresh().subscribe(async token => {
       console.log(token);
      ....
      ...
      });

    });
 }

 async presentToast(msg) {
   const toast = await this.toast.create({
      message: msg,
      duration: 3000,
      position: 'top'
   });
   await toast.present();
 }
2

There are 2 best solutions below

2
Akshay Nair On BEST ANSWER

async functions return promises and should return something to the calling function

...
this.presentToast(data.message);
...

does neither

so you have 2 options:

  1. modify the presentToast function like so:

      presentToast(msg) {
       const toast = this.toast.create({
       message: msg,
       duration: 3000,
       position: 'top'
    });
     toast.present();
    

    }

  2. consume the returned promise and present the toast function in the calling function

    ...
    initializeApp() {
    ...
       this.presentToast(data.message).then(data => 
           console.log('toast displayed')).catch(error => 
           console.log(error));
    ...
    
    async presentToast(msg) {
     this.toast.create({
    message: msg,
    duration: 3000,
     position: 'top'
    });
     return await toast.present();
    }
    
2
Misha Mashina On

Remove 'await' and just call toast.present().