2014-02-12 57 views
1

創建requestCounter服務我試圖讓這個我可以再補充「requestCounter」任何控制器,並獲得那就是不斷用請求的數量更新的值。攔截器代碼正在工作,但通過注入requestCounter提供的值始終爲{count: 0}。我不瞭解什麼!在angularjs

angular.module('theApp') 
    .provider('requestCounter', function ($httpProvider) { 
    this.$get = function() { 
     var activeRequests = 0; 
     var obj = {count: activeRequests}; 
     $httpProvider.defaults.transformRequest.push(function(data) { 
     activeRequests++; 
     return data; 
     }); 

     $httpProvider.defaults.transformResponse.push(function(data) { 
     activeRequests--; 
     return data; 
     }); 

     return obj; 
    }; 
    }); 

控制器

angular.module('theApp') 
    .controller('PurchaseCtrl', function ($scope, requestCounter) { 
    $scope.requests = requestCounter; 

    }); 

標記

<h1>There are {{requests.count}} requests loading</h1> 

回答

0

在開始的時候,你要分配activeRequests的原始值= 0到你的OBJ,所以它們不會相互鏈接。你可以嘗試:

var activeRequests = {number: 0}; 
var obj = {count: activeRequests}; 

然後你就可以在obj.count.number

+0

啊您的計數值,我看到我做錯了什麼。我只需要擺脫'activeRequests'因爲原語是通過值複製的。 'var obj = {count:0};'然後在攔截器中執行'obj.count ++'和'obj.count - '。謝謝! –