angularjs 邮件应用的长轮询

angularjs longpolling for mail app

我打算用 angular js 创建一个邮箱,这样我就有了一个服务和一个管理邮件的控制器。

服务

app.service('mails',['$http','$interval','$rootScope',function($http,$interval,$rootScope){
      var updatedData;
      $interval(function(){
        return $http.post('inc/get_mails.php?user='+'<?php echo $_SESSION['user']; ?>')
        .success(function(response){
          updatedData = response;
          alert(updatedData);
          $rootScope.$broadcast('got new mail!', { data: updatedData });
        })
        .error(function(err){console.log(err);});
      },1000);
    }]);

控制器

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

但我有一个问题,这个服务甚至 运行 1 次都没有。我应该怎么办!? :( 发送

您服务中的代码未被调用,您必须注入您的服务才能 运行 它。但我认为在您的服务中创建一个方法来初始化您的代码是更好的做法,它更明确。

app.factory('mails',['$http','$interval','$rootScope',function($http,$interval,$rootScope){

      var updatedData = [];

      return {
         init: init
      }

      function init() {
        $interval(function(){
          return $http.post('inc/get_mails.php?user='+'<?php echo $_SESSION['user']; ?>')
          .success(function(response){
            // check if their is a difference between this call and the last call
            if (updatedData.length !== response.length) {
               updatedData = response;
               alert(updatedData);
               $rootScope.$broadcast('got new mail!', { data: updatedData });
            }
          })
          .error(function(err){console.log(err);});
        },1000);
      }

    }]);

然后如果你想 运行 代码:

app.controller('yourCtrl', ['mails', '$scope', function(mails, $scope) {
   mails.init();

   // each time you have a new mail
   $scope.$on('got new mail!', function(event, args) {
       $scope.mails = args.data;
   });
}]);