如何从控制器重复调用 angularjs 服务来更新视图

How to call angularjs service repeatedly from controller to update the view

我正在尝试根据我的服务器响应每秒更新我的视图。我正在使用实时数据显示应用程序。我需要每秒向服务器发送请求并获取响应并显示到我的视图中。目前我正在使用 jquery 和 ajax 进行请求和响应。

刚才我正在尝试使用 angularjs 并使用下面的代码从服务器获取响应,

'use strict';

angular.module('liverate', ['dataServices']);

angular.module('dataServices', []).
service('Data', ['$http', function ($http) {
    var my_Date = new Date();
    var rates = {};
     var urlBase = BASE_URL+"api/apirate.php"+"?nocache=" + my_Date.getUTCSeconds();

     this.getRates = function () {
        $http({
              method: 'GET',
              url: urlBase,
              //headers: {'Content-Type': 'application/x-www-form-urlencoded'},
              success: function(data){
                   console.log(data);
                   rates = data;
              },
              error : function(statusCode,error) {
                  console.log(error);
              }
            });
        return rates;
     };
}]);

function LiverateController($scope, $timeout, Data) {
    $scope.data = [];
    var rates = {};
    (function tick() {
        $scope.data = Data.getRates(function(){
            $timeout(tick, 1000);
        });
    })();

    And also tried bellow method

    $scope.callAtTimeout = function() {
        console.log(Data.getRates());
    }

    $timeout( function(){ $scope.callAtTimeout(); }, 1000);

};

但这对我不起作用。只是它调用单个 time.How 我需要使用它。请任何人帮助我。

您似乎不太了解 $http/promises 的用法。您需要 return $http return 返回调用函数的承诺,或从该函数派生的承诺,例如以下代码:

angular.module('dataServices', []).
service('Data', ['$http', '$q', function ($http, $q) {
  var my_Date = new Date();
  var rates = {};
  var urlBase = BASE_URL+"api/apirate.php"+"?nocache=" + my_Date.getUTCSeconds();

  this.getRates = function () {
    return $http({
       method: 'GET',
       url: urlBase,
    }).then(function(results) {
       console.log(results);
       return results.data;
    }, function(error) {
       console.log(error);
       return $q.reject(error);
    });
  };
}]);

function LiverateController($scope, $timeout, Data) {
   $scope.data = [];
   var rates = {};
   (function tick() {
     Data.getRates().then(function(data){
       $scope.data = data;
     })['finally'](function() {
       $timeout(tick, 1000);
     });
   })();
};

还有

  • 我倾向于使用 $timeout 而不是 $interval,因为天真地使用 $interval 可能最终会破坏服务器,以防它有点慢

  • 调用$timeout实际上是在一个finally回调中,在请求成功和失败的情况下调用运行。