如何在angular js中使用setinterval每30秒刷新一次方法

时间:2019-03-25 11:57:48

标签: javascript angularjs

  

我有一个下拉列表,在ng-change事件中调用ajax调用并显示一些数据,但是我需要每30秒执行一次的方法。这样我就可以每30秒更新一次值   我做了刷新机制,但是有几个请求正在调用   的1。

     

第一次触发,之后触发两次   较早的请求数量,例如1,2,4,8,16,32,64次   执行

选择PIR设备

screenshot   选择PIR设备

 <th> <select class="form-control ng-pristine ng-valid ng-scope ng-empty ng-touched" ng-model="sel_val" ng-change="getPIRData(sel_val.deveui)" ng-options="data.deveui for data in Customers">Select PIR Device</select></th>

 var app = angular.module('PIR_Detection', []);
    app.controller('myCtrl', function ($scope, $http, $window) {
        $scope.sel_val = 0;
        $scope.DefaultLabel = "Loading.....";
        var post = $http({
            method: "get",
            url: "../data.json",
            dataType: 'json',
            data: {},
            headers: { "Content-Type": "application/json" }
        });
        post.success(function (data, status) {
            $scope.Customers = data;
        });
        post.error(function (data, status) {
        });

        $scope.getPIRData = function (id) {
            var url = "/PIRDetails/GetPIRStatus/" + id;

         setInterval(function () {
                        $scope.getPIRData(id);
                    }, 30000)     
            $http.get(url)
                .then(function (response) {
                    $scope.myWelcome = response.data;
                    $scope.pirstatus = base64toHEX($scope.myWelcome.dataFrame);
                    $scope.timestamp = getIST (response.data.timestamp);
                    $scope.rssi = response.data.rssi;

                });
        };

    });

1 个答案:

答案 0 :(得分:0)

这里的问题是您在响应过程中调用setInterval函数。

每次处理请求时,您每30秒安排一次新功能 scheduling ,而不是每30秒进行一次新功能调用。

$scope.getPIRData = function (id) {
            var url = "/PIRDetails/GetPIRStatus/" + id;


            $http.get(url)
                .then(function (response) {
                    $scope.myWelcome = response.data;
                    $scope.pirstatus = base64toHEX($scope.myWelcome.dataFrame);
                    $scope.timestamp = getIST (response.data.timestamp);
                    $scope.rssi = response.data.rssi;

                });
        };
setInterval(function () {
                        $scope.getPIRData(id);
                    }, 30000)  

我从响应处理的范围中删除了setInterval调用。现在应该可以了。