首页 > 解决方案 > 如何在我的应用中显示本地通知?

问题描述

我的代码如下所示:

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' }
    });
}

我收到此错误:Property 'notification' does not exist on type 'CordovaPlugins'

我想让代码在 Homepage 类之外。我从主页类中创建它,它没有给出错误,但它不会显示在我的设备上。我只想能够从主页外部调用函数 single_notification() 并显示通知。


编辑:使用 Emad Abdou 时遇到这些错误 答案: 在此处输入图像描述

标签: javascriptangularionic4

解决方案


首先,确保您已在 app.module.ts 提供程序中导入 LocalNotifications,然后在您的代码中尝试此操作

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' }
 });
}

检查文档以获取更多信息 https://ionicframework.com/docs/native/local-notifications


推荐阅读