2013-08-28 74 views
5

使用AngularJS 1.2如何從http攔截器進行廣播?

我的截擊看起來是這樣的:

 $httpProvider.interceptors.push(['$q', '$log', '$rootScope', function ($q, $log, $rootScope) { 
      return { 
       'request': function(config) { 
        $rootScope.$broadcast('spin'); 
        console.info('request!'); 
        return config || $q.when(config); 
       }, 
... 

在我的導航控制器(用來處理和裝載/微調結合的觀點):

$rootScope.$watch('spin', function(event) { 
    console.info('spin'); 
    $scope.spinner++; 
}); 

廣播似乎儘管我可以看到很多請求,但在收到的所有回覆結束時只發生一次!在控制檯日誌中輸入

我該如何管理我的全局微調器/加載器?

編輯 我希望在加載數據時在導航欄中顯示加載器/微調器。

+0

你想使用這個 –

+0

@Ajaybeniwal編輯要達到什麼:目的添加 – Tjorriemorrie

回答

4

$watch功能不監聽廣播消息。它注意範圍的變化。在這種情況下,只要$rootScope.spin發生更改,即調用(默認情況下)立即調用某個函數,這就是您調用一次的原因。

$on函數就是你想要的,因爲它是監聽廣播事件的東西。

$rootScope.$on('spin', function(msg, data) { 
    console.info('spin'); 
    $scope.spinner++; 
}); 

我已經把如果你是好奇一個完整的工作示例:

http://codepen.io/BrianGenisio/pen/wIBHz

3

而不是使用觀察家你應該只在模塊運行功能使用上

angular.module('test',[]).run(['$rootScope' function ($rootScope) { 
    $rootScope.$on("$spin", function() { 
     // set the spinner here 
    }); 

}]); 
+0

我在哪裏可以找到更多有關'run'和'$ on'和'$ broadcast'的信息? – Tjorriemorrie

+0

http://code.angularjs.org/1.2.0rc1/docs/api/angular.Module http://code.angularjs.org/1.2.0rc1/docs/api/ng.$ro​​otScope.Scope –