我创建了如下拦截器:
(function() {
'use strict';
angular.module('sbApp').factory('ErrorResponseInterceptor', ErrorResponseInterceptor).config(ErrorResponseInterceptorConfig);
ErrorResponseInterceptorConfig.$inject = [ '$httpProvider' ];
ErrorResponseInterceptor.$inject = [ '$rootScope', '$q', '$injector'];
function ErrorResponseInterceptorConfig($httpProvider) {
$httpProvider.interceptors.push('ErrorResponseInterceptor');
}
function ErrorResponseInterceptor($rootScope, $q, $injector) {
// Here I handle my http responses
}
})();
我在文件myService.js
中定义了其他服务,我想在上面的拦截器中使用此服务的方法,因此我在上面的代码中做了以下更改:
(function() {
'use strict';
angular.module('sbApp').factory('ErrorResponseInterceptor', ErrorResponseInterceptor).config(ErrorResponseInterceptorConfig);
ErrorResponseInterceptorConfig.$inject = [ '$httpProvider' ];
ErrorResponseInterceptor.$inject = [ '$rootScope', '$q', '$injector', 'myService'];
function ErrorResponseInterceptorConfig($httpProvider) {
$httpProvider.interceptors.push('ErrorResponseInterceptor');
}
function ErrorResponseInterceptor($rootScope, $q, $injector, myService) {
// Here I handle my http responses
}
})();
我遇到以下错误:
Uncaught Error: [$injector:unpr] Unknown provider: myServiceProvider <- myService <- ErrorResponseInterceptor <- $http <- $translateStaticFilesLoader
myService.js
代码:
(function() {
'use strict';
angular.module('sbApp').factory('myService', myService);
myService.$inject = [ '$rootScope', '$http', 'restAPIService', '$log',
'$filter', '$interval', '$location' ];
function myService($rootScope, $http, restAPIService, $log, $filter,
$interval, $location) {
......
return {
add : add,
};
.....
function add(module, event) {
var e = {
..........
}
.......
return $rootScope.myarray.push(e);
}
}
})();
是否允许将myService
用作拦截器,如何将其传递给拦截器?
答案 0 :(得分:1)
要在拦截器中获取服务对象的实例,请使用:
$injector.get('serviceName');
请尝试以下操作:
(function() {
'use strict';
angular.module('sbApp').factory('ErrorResponseInterceptor', ErrorResponseInterceptor).config(ErrorResponseInterceptorConfig);
ErrorResponseInterceptorConfig.$inject = [ '$httpProvider' ];
ErrorResponseInterceptor.$inject = [ '$rootScope', '$q', '$injector'];
function ErrorResponseInterceptorConfig($httpProvider) {
$httpProvider.interceptors.push('ErrorResponseInterceptor');
}
function ErrorResponseInterceptor($rootScope, $q, $injector) {
var myService = $injector.get('myService');
// Here I handle my http responses
}
})();