2014-12-05 78 views
0

我遇到了麻烦,试图用ngCordova和$ cordovaPush注册我的GCM regid。ngCordova在控制器内部获得GCM regid

我不能设法找回我的控制器中我REGID通过$ HTTP将其发送给我的API:

var gcmToken; 
gcmNotificationHandler = function(e) { 
    if (e.event === "registered") { 
     gcmToken = e.regid; 
     console.log(gcmToken); 
    } 
}; 
var aTonAvis = angular.module('aTonAvis', ['ngCordova']); 
aTonAvis.value('serverUrl', "http://atonavis.local/"); 
aTonAvis.controller('RegisterCtrl', function($scope, $cordovaPush, 
    $cordovaDevice, $http, serverUrl) { 
    var gcmConfig = { 
     "senderID": "00000000000" 
    }; 
    var iosConfig = { 
     "badge": "true", 
     "sound": "true", 
     "alert": "true", 
    }; 
    gcmConfig.ecb = "gcmNotificationHandler"; 
    iosConfig.ecb = "iosNotificationHandler"; 
    var configHandler = function() { 
     if ($cordovaDevice.getPlatform().toLowerCase() === 
      'android' || $cordovaDevice.getPlatform() === 
      'amazon-fireos') { 
      return gcmConfig; 
     } else { 
      return iosConfig; 
     } 
    }; 
    this.registered = false; 
    document.addEventListener("deviceready", function onDeviceReady() { 
     $cordovaPush.register(configHandler()).then(function(
      result) { 
      console.log("Inside register " + gcmToken); 
      var pushToken; 
      if ($cordovaDevice.getPlatform().toLowerCase() === 
       'ios') pushToken = result; 
      else pushToken = gcmToken; 
      $http.post(serverUrl + 'api/setdevice', { 
       token: pushToken, 
       device: $cordovaDevice.getPlatform(), 
       version: $cordovaDevice.getVersion(), 
       model: $cordovaDevice.getModel() 
      }).success(function(data, status, 
       headers, config) { 
       this.registered = true; 
      }); 
     }, function(err) { 
      console.log("Registering Error : " + err); 
     }); 
    }); 
}); 

的。那么函数在gcmNotificationHandler之前解雇,所以我gcmToken是不确定的,和这里的我在我的日志中得到:

Inside register : undefined app.js:41 
APA91bEzVUk3T1T6WpIsEHOq43hCh_pZeBPjRDPSPxV2j6VjVW-KcUepbmf6snaCiqGvYp3H_XYHIXQdbVtvMF3t-NtoZJaJzV9FkNtUlutuWYs5XPAZ-H1ixQnAyhTO6fAPDMn7Ef5f5HgBR9fgWpmXc0u_xBM4yKvoXCnVXEG18IZV2hvY app.js:6 

我不知道我在做什么错在这里,任何人都可以帮忙吗?

回答

0

这里是我的代码,使用ngCordova与PushPlugin。 regid与android的事件“pushNotificationReceived”具有相同的回调。以下是我在该事件的回调中使用的代码,以接收来自GCM的regid:

检查(notification.event ==='registered')是最重要的。

$rootScope.$on('pushNotificationReceived', function(event, notification) { 

    //console.log("result: " + JSON.stringify(event)); 
    console.log("result: " + JSON.stringify(notification));   

    console.log('Success: Inside the push notification received callback with this payload JSON' + notification); 

    if((platform == 'android' || platform == 'Android') && notification.regid && (notification.event === 'registered')) 
    { 
    var googDevToken = notification.regid; 
    console.log(googDevToken); 
    } 

});