Sandro Antonucci
Sandro Antonucci

Reputation: 1753

Push notifications in ngCordova/Ionic, getting just "OK"

I'm trying for the first time to create an hybrid app using this example code for Android. I'm testing to see if I can get notifications to work and I'm getting two errors:

  1. The result object you should get it doesn't contain anything but just OK

  2. I'm getting $rootScope is not defined, where should I define it?

My code is

var app = angular.module('starter', ['ionic', 'ngCordova']);

app.run(function($cordovaPush) {

  var androidConfig = {
    "senderID": "84xxxxxxxx",
  };

  document.addEventListener("deviceready", function(){
    $cordovaPush.register(androidConfig).then(function(result) {
      // Success
      console.log("OK, result is " + result);
    }, function(err) {
      // Error
      console.log("NOT OK");
    })

    $rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
      switch(notification.event) {
        case 'registered':
          if (notification.regid.length > 0 ) {
            alert('registration ID = ' + notification.regid);
          }
          break;

        case 'message':
          // this is the actual push notification. its format depends on the data model from the push server
          alert('message = ' + notification.message + ' msgCount = ' + notification.msgcnt);
          break;

        case 'error':
          alert('GCM error = ' + notification.msg);
          break;

        default:
          alert('An unknown GCM event has occurred');
          break;
      }
    });


    // WARNING: dangerous to unregister (results in loss of tokenID)
    $cordovaPush.unregister(options).then(function(result) {
      // Success!
    }, function(err) {
      // Error
    })

  }, false);
});

Upvotes: 0

Views: 300

Answers (1)

Mudasser Ajaz
Mudasser Ajaz

Reputation: 6257

Include $rootScope in .run() like this

app.run(function($cordovaPush,$rootScope) {

And result in register response is not of any use to you.In case of success of registration you will receive an event registered, what you need is registration id, which you will receive here as notification.regid.

 case 'registered':
          if (notification.regid.length > 0 ) {
            alert('registration ID = ' + notification.regid);
          }
          break;

Upvotes: 1

Related Questions