saleh asadi saleh asadi - 4 months ago 10
Ajax Question

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

Answer

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){
            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', function(mails) {
   mails.init();
}]);