Reputation: 8079
I've created an $httpProvider
interceptor, like the one described here:
$httpProvider.interceptors.push(function ($q) {
return {
'responseError': function (response) {
var _status,
_message;
switch (response.status) {
case 403:
_status = 'warning';
_message = 'no rights to do this';
break;
case 500:
_status = 'danger';
_message = 'internal server error';
break;
}
Alert.add({status: _status, msg: _message});
return $q.reject(response);
}
};
});
Alert
is a service I've reated to display notifications, errors etc. It depends on $rootScope
and simply adds an object to be rendered in html.
So the question is: how do I call my Alert
service from app.config
where this interceptor is defined? Or, if it's not possible, how can I catch all http errors in one place and display them?
Upvotes: 2
Views: 58
Reputation: 136144
You need to use $injector
and then inside the interceptor you could get the service by doing $injector.get
any service name.
Code
$httpProvider.interceptors.push(function ($q, $injector) {
return {
'responseError': function (response) {
var service = $injector.get('myService'); //here you can get service
var _status,
_message;
switch (response.status) {
case 403:
_status = 'warning';
_message = 'no rights to do this';
break;
case 500:
_status = 'danger';
_message = 'internal server error';
break;
}
Alert.add({status: _status, msg: _message});
return $q.reject(response);
}
};
});
Update
As per @zeroflagL solution It would work in simpler way by only dependency injection of service directly in function.
Code
$httpProvider.interceptors.push(function ($q, myService) {
return {
'responseError': function (response) {
var _status,
_message;
switch (response.status) {
case 403:
_status = 'warning';
_message = 'no rights to do this';
break;
case 500:
_status = 'danger';
_message = 'internal server error';
break;
}
Alert.add({status: _status, msg: _message});
return $q.reject(response);
}
};
});
Upvotes: 1