2016-08-01 7 views
2

メールを管理するサービスとコントローラがあるので、私は角度jsのメールボックスを作るつもりです。メールアプリケーション用のanglejs longpolling

サービス

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時間に実行されない問題を抱えています。私は何をすべきか!? :( tnx

答えて

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

を私はコードの変更に気づいていなかったあなたの答えに感謝し、私はそれをチェックアウトします –

+0

私はちょうど私の更新。。工場コードを使用する – Gatsbill

+0

ありがとうございます多くのGatsbill、あなたのinitメソッドは魔法を作った:D。今それは働いている。 –

関連する問題