Reputation: 1055
I'm new to angular and kind of lost right now. I have a provder that handles if server sends response or not and then I do some stuff based on it.
Here is the provider code
define(['angular', '../module'], function (angular, module) {
return module.provider('httpProvider', ['$httpProvider', function ($httpProvider) {
var interceptor = ['$q', '$rootScope', function ($q, $rootScope) {
return {
response: function (response) {
$rootScope.serverError = true;
return response;
},
responseError: function (rejection) {
if (rejection.status === 0) {
$rootScope.serverError = true;
}
return $q.reject(rejection);
},
};
}];
$httpProvider.interceptors.push(interceptor);
}]);
});
And it throws error:
Provider 'httpProvider' must define $get factory method.
Any idea?
EDIT:
Here is how my factory looks now, and its created fine, but I can not inject it into config
define(['angular', './module'], function (angular, module) {
module.factory('httpInterceptor', function () {
var interceptor = ['$q', '$rootScope', function ($q, $rootScope) {
return {
response: function (response) {
$rootScope.serverError = true;
return response;
},
responseError: function (rejection) {
if (rejection.status === 0) {
$rootScope.serverError = true;
}
return $q.reject(rejection);
}
};
}];
return interceptor;
});
});
In module config I use it this way:
$httpProvider.interceptors.push('httpInterceptor');
But it actually push to the array just a string ( who would expect that right? D: ) and nothing is happening. I've changed the factory to always has serverError set to true, so I can test it, but it will actually do nothing, so it means that response or responseError functions are never called.
Any idea?
Upvotes: 1
Views: 1221
Reputation: 1055
Ok, I've been able to fix it, I figure out that I've created the factory wrong way, the right one is this:
define(['angular', './module'], function (angular, module) {
module.factory('httpInterceptor',['$q', '$rootScope', function ($q, $rootScope) {
return {
'request': function(config) {
return config;
},
'response': function (response) {
$rootScope.serverError = false;
return response;
},
'responseError': function (rejection) {
if (rejection.status === 0) {
$rootScope.serverError = true;
}
return $q.reject(rejection);
}
};
}]);
});
In config of module I use:
$httpProvider.interceptors.push('httpInterceptor');
Thanks all of you for help.
Upvotes: 0
Reputation: 96
Here is how you should create interceptors:
angular.module('myApp', []).
config(function($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
});
angular.module('myApp').
factory('myInterceptor', function() {
return {
//interceptor object
};
});
Upvotes: 0