2015-11-11 51 views
1

我正在嘗試在Angular中編寫一個應用程序,每10秒更新一次數據。我的問題是,每次刷新我的頁面時,函數只會被調用一次。

console.log只是爲了確保該函數只被調用一次。

這是我發起的間隔碼:

var app = angular.module('myApp',['ngRoute', 'ui.bootstrap', 'ngNotify', 'ngTagsInput', 'djds4rce.angular-socialshare']); 

app.run(function($FB, $http, $rootScope, $interval){ 
    $FB.init('527807327395199'); 
    $interval(function() {callAtInterval($http, $rootScope)}, 1000, true); 
    $rootScope.count = 0; 
}); 


function callAtInterval($http, $rootScope) { 
    $http.get("/points-for-school") 
    .then(function(response){ 
    $rootScope.schoolCompetitionPoints = response.data; 
    console.log($rootScope.count++); 
    console.log(response); 
    }, function(response){ 
    console.error(response); 
    }); 
} 

的是,我這個在app.run方法的問題?

我必須將代碼放入控制器才能正常工作嗎?

如果有一種方法可以在不創建控制器的情況下完成這項工作,我更喜歡它。

回答

0

我設法解決這個問題。間隔服務可以有四個參數:

$service(function, delay, count, invokeApply, pass) 

最後三個參數是可選的。我的代碼存在的問題是,我發送的「真實」參數被讀取爲值爲1的計數,因此只執行一次函數。有兩種方法可以解決這個問題,並且:1.刪除「true」參數,因爲它默認爲true。 2.指定計數未定義

這裏是我用來做它的工作代碼:

app.run(function($FB, $http, $rootScope, $interval){ 
    $FB.init('527807327395199'); 
    $interval(function() { callAtInterval($http, $rootScope, undefined, true);}, 1000); 
    $rootScope.count = 0; 
}); 


function callAtInterval($http, $rootScope) { 
    $http.get("/points-for-school") 
    .then(function(response){ 
    $rootScope.schoolCompetitionPoints = response.data; 
    console.log($rootScope.count++); 
    console.log(response); 
    }, function(response){ 
    console.error(response); 
    }); 
} 
3

$interval()以函數作爲參數,以便每10秒調用一次該函數。

但是你沒有傳遞一個函數作爲參數。你是致電callAtInterval($http, $rootScope),並將此呼叫返回的值(undefined)傳遞給$interval()。所以你有效地要求$ interval每隔10秒呼叫undefined

你真正想要的是

$interval(function() { 
    callAtInterval($http, $rootScope); 
}, 1000, true); 
+0

是的,這是真的。我相應地根據你的建議改變了代碼,但它仍然只被調用一次。 – kitkong

+1

你需要添加count參數,就像我在我的答案中寫的一樣。感謝您的幫助,但它幫助我解決了第一個問題,就是我如何通過該功能。 – kitkong

相關問題