Angularjs 如何定期自动调用$http请求

Angularjs 如何定期自动调用$http请求,angularjs,Angularjs,我有一个带有角度前端的MVC web应用程序。我希望视图通过触发一个函数自动更新其内容,该函数在设置的时间间隔内发出角度$http请求 我很确定我有所有需要的部件来完成这项工作,但我似乎无法将它们装配在一起 这就是我目前正在尝试的 角度: app.controller("processModel", function ($scope, $http, $interval) { $scope.GetData = function () { $interval($scope.

我有一个带有角度前端的MVC web应用程序。我希望视图通过触发一个函数自动更新其内容,该函数在设置的时间间隔内发出角度$http请求

我很确定我有所有需要的部件来完成这项工作,但我似乎无法将它们装配在一起

这就是我目前正在尝试的

角度:

app.controller("processModel", function ($scope, $http, $interval) {

    $scope.GetData = function () {
        $interval($scope.LoadData, 3000);
    }

    $scope.LoadData = function() {
        $http({
            method: "GET",
            url: 'Home/DataRefresh'
        }).then(function success(response) {
            $scope.data = response.data;
        }, function error(errResponse) {
            alert("ERROR!");
        });
    };  
});
HTML:

<div class="jumbotron" style="margin-bottom:0; padding-top:10px;" ng-init="GetData()">

    <tr ng-repeat="item in data">

        <td>{{item.info}}</td>

    </tr>

<div>

非常奇怪的是,它确实进入了
警报(“进入成功响应”)每3秒一次,但操作方法仅在第一次被命中。我不明白为什么会出现这种情况。

我建议不要使用
ng init
触发间隔,而是直接调用
$interval($scope.LoadData,3000)从控制器内部。正如建议的那样,ng init的使用应该限制在非常特定的用例中。对于总是失败的请求,首先检查您可以手动调用它,并且控制台中没有任何错误。并检查网络检查器以查看请求的错误代码。它可能会给你一些提示。是的,当我手动调用它一次(只是删除$interval包装器)时,它会一致地工作并加载找到的数据。我试着将$interval放在一堆不同的地方,并尝试以几种不同的方式调用控制器,但我无法让它循环并重复调用。如何从HTML中触发该间隔而不将其绑定到某个指令?该错误是一般性的,因为您忽略了
errResponse
对象,这将为您提供大量提示,说明它为什么不起作用。对于这样多的请求,使用服务器负载会更好websockets@charlietfl我扩展了错误的各个部分,没有得到任何特别有用的东西。事实上,我已经找到了如何在一个时间间隔内可靠地触发LoadData调用的方法,但是出于某种原因,Action方法只在第一次被命中,即使所有后续的时间间隔都进入了$http调用的“success return”分支。OP更新。
app.controller("processModel", function ($scope, $http, $interval) {
    $scope.LoadData = function() {
        $http({
            method: "GET",
            url: 'Home/REIDataRefresh'
        }).then(function success(response) {
            $scope.data = response.data;
            alert("Got into the success response");
        }, function error(errResponse) {
            alert("data " + errResponse.data + " status " + errResponse.status + " headers " + errResponse.headers + "config " + errResponse.config + " statusText " + errResponse + " xhrStat " + errResponse.xhrStatus);
        });
    };  

    $interval($scope.LoadData, 3000);
});