我想拦截所有http错误消息并向用户提供视觉反馈。为此,我想做这样的事情
.config(function($httpProvider) {
$httpProvider.interceptors.push(function($q) {
return {
'responseError': function(rejection) {
// show visual feedback or emit an event.
return $q.reject(rejection);
...
但是,我无法注入$rootScope
(执行$rootScope.$emit()
),因为这是 config 块。出于同样的原因,也不可能注射角咆哮或类似的包装。如何解决这个用例?
答案 0 :(得分:4)
您可以将$ rootScope与$ q一起注入:
.config(function($httpProvider) {
$httpProvider.interceptors.push(function($q, $rootScope) {
return {
'responseError': function(rejection) {
// show visual feedback or emit an event.
$rootScope.$emit( ... );
return $q.reject(rejection);
答案 1 :(得分:2)
尝试这样的事情
angular.module('interceptor.http', [])
.config(function ($httpProvider) {
$httpProvider.responseInterceptors.push('errorInterceptor');
})
.factory('errorInterceptor', function ($q, $rootScope) {
return function (promise) {
return promise.then(function (response) { },
function (response) {
$rootScope.$broadcast("error",{statusCode : 'error'});
return $q.reject(response);
});
};
});
答案 2 :(得分:1)
...您可以注入$rootScope
。我不知道你在说什么。但是,如果您想在运行时注入依赖项,否则需要一个可以创建循环依赖项的服务,您可以在配置块中使用$injector
服务,如下所示:
// ... other angular code
.config(function($httpProvider){
$httpProvider.interceptors.push(function($q, $injector){
return {
responseError: function(arg1, arg2, argWhatever){
// This isn't run until there's actually an error (everything has already been configured)
// This is totally allowed
$http = $injector.get('$http');
// ... do whatever with your service
return $q.reject(/*something here*/);
}
};
});
});