全局$ http.get()在Angular 1.5

时间:2016-02-21 03:56:20

标签: angularjs angularjs-service

在我的Angular项目中,我从我的api加载json列表,不断更新。我想在所有角度控制器上每隔5秒进行一次更新,而不是每个控制器都有新的请求。

1 个答案:

答案 0 :(得分:2)

为什么不让服务在$interval上进行API调用,然后$broadcast在每次履行带有更新数据的承诺时发送消息和数据。

angular.module('app')
  .service('PollingService', ['$http', '$rootScope', '$interval', function($http, $rootScope, $interval) {

    var updatedData;

    $interval(function() {
      return $http.get(apiUrl).then(function successCallback(response) {
        updatedData = response.data.data;
        $rootScope.$broadcast('got new data!', { data: updatedData });
      }, function failureCallback(reason) {
        console.log(reason);
      })
    }, 5000);

  }]);

然后在需要更新数据的所有控制器中监听广播:

angular.module('app')
  .controller('someCtrl', ['$scope', function($scope) {

    $scope.$on('got new data!', function(event, args) {
      $scope.data = args.data;
    });

  }]);