Search code examples
javascriptangularionic4

How to display a local notification in my app?


My code looks like this:

import { LocalNotifications } from '@ionic-native/local-notifications';

@Component({
    selector: 'app-home',
    templateUrl: 'home.page.html',
    styleUrls: ['home.page.scss'],
})
export class HomePage {
    framework = 'At exact boarding time';

    constructor(public platform: Platform) {}

    ionViewDidEnter() {
        this.platform.ready().then(() => {
            single_notification()
        });
    }
}

function single_notification() {
    cordova.plugins.notification.local.schedule({
      id: 1,
      text: 'Single ILocalNotification',
      sound: 'file://sound.mp3',
      data: { secret: 'key_data' }
    });
}

I get this error: Property 'notification' does not exist on type 'CordovaPlugins'

I would like to have the code be outside of the Homepage class. I created it from within the homepage class, and it gave no errors, but it would not display on my device. I just want to be able to call the function single_notification() from outside the Homepage and display a notification.


edit: getting these errors when using Emad Abdou answer: enter image description here


Solution

  • First, Make sure you have imported LocalNotifications in your app.module.ts providers then in your code try this

    import { LocalNotifications } from '@ionic-native/local-notifications/ngx';
    
    @Component({
      selector: 'app-home',
      templateUrl: 'home.page.html',
      styleUrls: ['home.page.scss'],
    })
    export class HomePage {
     framework = 'At exact boarding time';
    
     constructor(
          public platform: Platform,
          private localNotifications: LocalNotifications) {}
    
    ionViewDidEnter() {
        this.platform.ready().then(() => {
            this.single_notification()
        });
      }
    }
    
    single_notification() {
      this.localNotifications.schedule({
       id: 1,
       text: 'Single ILocalNotification',
       sound: 'file://sound.mp3',
       data: { secret: 'key_data' }
     });
    }
    

    Check documentation for more info https://ionicframework.com/docs/native/local-notifications