$interval函数在AngularJS应用程序中仅调用一次

$interval函数在AngularJS应用程序中仅调用一次,angularjs,Angularjs,我正在尝试用Angular编写一个应用程序,它每10秒更新一次数据。我的问题是,每次刷新页面时,该函数只被调用一次 log只是为了确保函数只被调用一次 这是我启动间隔的代码: var app = angular.module('myApp',['ngRoute', 'ui.bootstrap', 'ngNotify', 'ngTagsInput', 'djds4rce.angular-socialshare']); app.run(function($FB, $http, $rootScope

我正在尝试用Angular编写一个应用程序,它每10秒更新一次数据。我的问题是,每次刷新页面时,该函数只被调用一次

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方法中执行此操作吗

我是否必须将代码放入控制器才能工作

如果有一种方法可以在不创建控制器的情况下实现这一点,我会选择它。

$interval()
将函数作为参数,以便每10秒调用一次函数

但你不能把函数作为参数传递。您正在调用
callAtInterval($http,$rootScope)
,并将此调用返回的值(
未定义的
)传递给
$interval()
。因此,您实际上要求$interval每隔10秒调用
undefined

你真正想要的是

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

我设法解决了这个问题。间隔服务可以有四个参数:

$service(function, delay, count, invokeApply, pass)
最后三个参数是可选的。我的代码的问题是,我发送的“true”参数被读取为值为1的count,因此只执行了一次函数。解决这个问题有两种方法: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);
  });
}

我知道已经很晚了,可能有一些人对此感兴趣。在angularjs的旧版本中,JB Nizet可能是对的。现在有必要作为参数通过多次重复

$interval(函数(){
callAtInterval($http,$rootScope);
},1000,0,对)

参数0将无限期重复


这是。

是的,没错。我根据您的建议更改了代码,但仍然只调用了一次。您需要添加count参数,就像我在回答中所写的那样。不过谢谢你的帮助,它帮助我解决了第一个问题,那就是我是如何传入函数的。