Unhandled Promise rejection: push.on is not a func

2019-06-20 08:35发布

问题:

I am using Ionic 2.

I get this Typescrpt error when trying to set up Push Notifications. I have copied this sample code from a tutorial, so would have expected it to work. I must have something wrong. Any ideas please:

Unhandled Promise rejection: push.on is not a function ; Zone: angular ; Task: Promise.then ; Value:
TypeError: push.on is not a function


push.on('registration', function (data) {

typescript

import { Push } from 'ionic-native';

. .

  pushNotifications(): void {

    var push = Push.init({
      android: {
        vibrate: true,
        sound: true,
        senderID: "xxxxxxxxxxxxxxxxxxx"
      },
      ios: {
        alert: "true",
        badge: true,
        sound: 'false'
      },
      windows: {}
    });

    push.on('registration', (data) => {
      console.log(data.registrationId);
      alert(data.registrationId.toString());
    });
    push.on('notification', (data) => {
      console.log(data);
      alert("Hi, Am a push notification");
    });
    push.on('error', (e) => {
      console.log(e.message);
    });

  }

回答1:

Make sure to check if 'window.cordova' is available before using the plugin. Are you actually testing on a device or in browser? Cordova is not available within browser.

EDIT To make sure your code editor knowns what 'window.cordova' is, make sure you installed cordova typings.

npm install typings -g
typings install dt~cordova --save --global