Angularjs 在$rootScope中的条件集上使用HTTP侦听器
我使用以下方法定义HTTP侦听器服务:Angularjs 在$rootScope中的条件集上使用HTTP侦听器,angularjs,Angularjs,我使用以下方法定义HTTP侦听器服务: fooModule.service('myHttpInterceptor', function ($q, $rootScope) { // ... }) 我能够在config块中将其推入$httpProvider,拦截器工作并始终处于启用状态: .config(['$httpProvider', function($httpProvider) { $httpProvider.interceptors.push('myHttpInterce
fooModule.service('myHttpInterceptor', function ($q, $rootScope) {
// ...
})
我能够在config
块中将其推入$httpProvider,拦截器工作并始终处于启用状态:
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('myHttpInterceptor');
}]);
但我无法基于加载在$rootScope
中的配置启用拦截器:
.config(['$httpProvider', function($httpProvider, $rootScope) {
// $rootScope is undefined.
如果使用.run
而不是.config
,则无法使用$httpProvider
只有在设置了$rootScope中的变量时,我才能使用HTTP侦听器。您不能-您只能将提供程序注入配置函数,因为它们在创建依赖项之前运行 但是,您可以做的是更改
myHttpInterceptor
,在执行任何自定义侦听器逻辑之前检查根作用域上的属性。这样,当未设置属性时,拦截器将不会执行任何操作
仅当设置了$rootScope中的变量时,如何使用HTTP侦听器
要避免污染$rootScope,请向拦截器工厂添加属性:
在继续之前,编写拦截器以检查myInterceptEnable
属性:
app.factory('myHttpInterceptor', function() {
return {
'myInterceptEnable': false,
// optional method
'request': function(config) {
if (!this.myInterceptEnable) return config;
// do something on success
return config;
},
// optional method
'requestError': function(rejection) {
if (!this.myInterceptEnable) throw rejection;
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return throw rejection;
},
// optional method
'response': function(response) {
if (!this.myInterceptEnable) return response;
// do something on success
return response;
},
// optional method
'responseError': function(rejection) {
if (!this.myInterceptEnable) throw rejection;
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return throw rejection;
}
};
});
然后,可以通过设置myHttpInterceptor.myInterceptEnable
或true
或false
来打开或关闭拦截器
app.run(function(myInterceptor) {
myInterceptor.myInterceptEnable = true;
});
谢谢@GregL我想这是一个不错的选择,我只是希望我能让拦截器尽可能模块化。让它依赖于
$rootScope
属性并不是特别模块化的<代码>$rootScope几乎和全局范围一样糟糕。但我很高兴我帮助您确认了唯一真正的解决方案。为了澄清,我的意思是模块化,因为它可以应用于一个客户机,但不能应用于另一个客户机(两者使用相同的代码库)。客户端配置是$rootScope中加载的内容,拦截器依赖于@GregL。