簡體   English   中英

從angularjs外部運行工廠中包含的功能

[英]run a function contained within a factory from outside angularjs

首先,這與這里的幾個問題非常相似,但是沒有一個答案對我有用。

我有一個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失敗:錯誤:TypeError:未定義不是函數”和類似錯誤。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM