2014-02-12 3 views
1

모든 컨트롤러에 "requestCounter"를 추가하고 요청 수와 함께 지속적으로 업데이트되는 값을 얻을 수 있도록하기 위해 노력 중입니다. 인터셉터 코드가 작동하지만 requestCounter를 주입하여 제공된 값은 항상 {count: 0}입니다. 나는 이해하지 못한다!angularjs에서 requestCounter 서비스 만들기

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의 프리미티브 값 귀하의 OBJ에 = 0을 할당하는, 그래서 그들은 서로 연결되어 있지 않습니다 . 당신이 시도 할 수 있습니다 :

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

는 그런 다음 obj.count.number

+0

아에 계산을 가질 수, 난 내가 뭘 잘못했는지를 참조하십시오. 프리미티브가 값에 의해 복사되기 때문에'activeRequests'를 제거하면된다. 'var obj = {count : 0};'그리고 인터셉터에서'obj.count ++'와'obj.count -'를합니다. 고마워! –

관련 문제