1

Firstly this is very similar to several questions here but none of the answers have worked for me.

I have an Cordova/AngularJS/Ionic app which every 10 mins polls a remote server and pulls down some JSON - this works fine. I also have push notifications with the PhoneGap Build plugin, again working fine. What I want to do is connect the two such that when a notifications comes in it fires my poller thus getting the latest content in between the poll times.

Existing functioning code:

var schoolApp = angular.module('schoolApp', ['ionic',  'schoolApp.controllers', 'schoolApp.services'])

schoolApp.run(function(Poller) {});


.factory('Poller', function($http, $interval,updateContentLocalStorage) {
      var pollerFunct = function() {  
        // fetch and process some JSON from remote server

       } // END pollerFunct()




    // run on app startup, then every pollTimeout duration 
    // delay by 10sec so that checkConnectionIsOn() has time to settle on browser platform - seems not needed in actual devices but no harm to delay there too
    setTimeout(function(){ pollerFunct(); }, 10000);
    //pollerFunct(); // run on app startup, then every pollTimeout duration
    $interval(pollerFunct, pollTimeout);

}) // END factory Poller

Push notification processing, outside of Angular

// handle GCM notifications for Android
function AndroidOnNotification(e) {
    //  working: call angular service from outside angular: http://stackoverflow.com/questions/15527832/how-can-i-test-an-an-angularjs-service-from-the-console
    var $http = angular.element(document.body).injector().get('$http');
    var $state = angular.element(document.body).injector().get('$state');

    // not working : http://stackoverflow.com/questions/26161638/how-to-call-an-angularjs-factory-function-from-outside 
    angular.element(document.body).injector().get('Poller').pollerFunct();

}

I want to call the pollerFunct() from AndroidOnNotification(e) but getting "processMessage failed: Error: TypeError: undefined is not a function " and similar errors.

KevInSol
  • 2,560
  • 4
  • 32
  • 46
  • Your factory returns nothing, and pollerFunct is just a local var (It can not be addressed even from angular). Have you tried smth like in Poller: var factory ={}; factory.pollerFunct = function() {...} return factory. – Petr Averyanov Mar 23 '15 at 12:52

1 Answers1

1

@Petr's comment re returning nothing led me to examine other parts of my code I'd forgotten about and this works:

.factory('Poller', function() {
      var pollerFunct = function() {
        // fetch and process some JSON from remote server
       } 

    // return something
    return { 
          poll: function() {
             pollerFunct();
             return; 
          }
        }   
}) 

Called by:

angular.element(document.body).injector().get('Poller').poll();
KevInSol
  • 2,560
  • 4
  • 32
  • 46