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

时间:2015-11-11 15:24:00

标签: angularjs

我正在尝试在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方法中执行此操作?

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

如果有一种方法可以在不创建控制器的情况下完成这项工作,我会更喜欢它。

3 个答案:

答案 0 :(得分:3)

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

但是你并没有将函数作为参数传递。您已致电 callAtInterval($http, $rootScope),并将此次调用(undefined)返回的值传递给$interval()。因此,您有效地要求$ interval每隔10秒拨打undefined

你真正想要的是

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

答案 1 :(得分:1)

我知道已经很晚了,也许有些人对此感兴趣。 JB Nizet可能是正确版本的angularjs。现在有必要作为参数表传递多次。

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

参数0将无限期重复。<​​/ p>

这里是doc

答案 2 :(得分:0)

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

$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);
  });
}