Search code examples
javascriptjqueryangularjsajaxlong-polling

angularjs longpolling for mail app


I'm going to make a mailbox with angular js so i have a service and a controller that manage the mails.

Service

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);
    }]);

Controller

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

but i have a problem this service does not run even 1 time. what should i do!? :( tnx


Solution

  • The code in your service is not called, you have to inject your service in order to run it. But I think it's a better practice to create a method in your service to init your code, it's more explicit.

    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);
          }
    
        }]);
    

    And then if you want to run the code :

    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;
       });
    }]);