【问题标题】:run a function contained within a factory from outside angularjs从 angularjs 外部运行工厂中包含的函数
【发布时间】:2015-05-26 10:46:28
【问题描述】:

首先,这与这里的几个问题非常相似,但没有一个答案对我有用。

我有一个 Cordova/AngularJS/Ionic 应用程序,它每 10 分钟轮询一次远程服务器并下拉一些 JSON - 这很好用。我也有使用 PhoneGap Build 插件的推送通知,再次正常工作。我想要做的是将两者连接起来,这样当收到通知时,它会触发我的轮询器,从而在轮询时间之间获取最新内容。

现有功能代码:

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

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();

}

我想从 AndroidOnNotification(e) 调用 pollerFunct() 但得到“processMessage failed: Error: TypeError: undefined is not a function”和类似的错误。

【问题讨论】:

  • 您的工厂什么也不返回,而 pollerFunct 只是一个本地变量(即使从角度也无法解决)。你有没有在 Poller 中尝试过类似的东西:var factory ={}; factory.pollerFunct = function() {...} 返回工厂。

标签: javascript angularjs cordova factory


【解决方案1】:

@Petr 的评论没有返回任何内容,这让我检查了我忘记的代码的其他部分,这很有效:

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

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

调用者:

angular.element(document.body).injector().get('Poller').poll();

【讨论】:

  • 非常感谢 :)
猜你喜欢
  • 2014-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
  • 2015-11-20
  • 1970-01-01
相关资源
最近更新 更多