2013-12-10 36 views
0

我喜歡在每次請求完成時顯示警告框。爲了縮短我的方式,我喜歡使用'Bootstrap Alert'。似乎沒有辦法訪問工廠內的任何範圍。我怎麼能認識到這樣的事情?AngularJS Http攔截器,顯示引導警報

app.factory('httpInterceptor', function ($q) { 
    return { 
     // On request success 
     request: function (config) { 
      $scope.alerts.push({msg: "Request done !"}); //There is no scope 
      return config || $q.when(config); 
     }, 
     // On request failure 
     requestError: function (rejection) { 
      return $q.reject(rejection); 
     }, 
     // On response success 
     response: function (response) { 
      return response || $q.when(response); 
     }, 
     // On response failure 
     responseError: function (rejection) { 
      return $q.reject(rejection); 
     } 
    }; 
}); 

請參閱警報例如在http://angular-ui.github.io/bootstrap/

+2

我想你可以在這裏注入$ rootScope。嘗試一下。使用$ rootScope。$ broadcast方法來引發一個事件,並在一些控制器中捕獲它以顯示更晚的事件。 – Chandermani

回答

1

您可以創建將注入攔截服務和範圍:

.factory('alerts', 

function() { 

    var alerts = []; 

    return { 

     getAlerts: function() { 
      return alerts; 
     }, 

     addAlert: function (msg) { 
      alerts.push({ msg: msg }); 
     }, 

     closeAlert: function (index) { 
      alerts.splice(index, 1); 
     } 
    } 
}) 

在範圍內的控制器使用這樣的:

function($scope, alerts) { 
    $scope.alerts = alerts.getAlerts(); 
} 

而在攔截器本身:

alerts.addAlert('msg'); 
1

我知道這個問題是相當古老的,也許OP已經找到了更好的解決方案,但我在這裏提供了答案,作爲對那些沒有找到解決方案的人的參考。

我們可以利用$廣播方法可用與引導。瞭解更多關於$播出位置:https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope#$廣播

app.factory('httpInterceptor', function ($q) { 
    return { 
     // On request success 
     request: function (config) { 
      $rootScope.$broadcast("requestDone");    
      return config || $q.when(config); 
     }, 
     // On request failure 
     requestError: function (rejection) { 
      return $q.reject(rejection); 
     }, 
     // On response success 
     response: function (response) { 
      return response || $q.when(response); 
     }, 
     // On response failure 
     responseError: function (rejection) { 
      return $q.reject(rejection); 
     } 
    }; 
}); 

在你的控制器,只聽的事件爲:

$rootScope.$on("loginStatus", function(e) { 
    $scope.alerts.push({msg: "Request done !"}); //There is scope 
}); 

乾杯!