Reputation: 6943
I have an angular service that looks like:
service('PortfolioService', ['$resource', function($resource) {
return $resource('/api/', {}, {
stock_positions: {
method: 'GET',
url: '/api/stock_positions',
isArray: false
}
});
}]).
And in a controller:
PortfolioService.stock_positions(function someCB(result){
//do something with the result
});
If you aren't logged in the api returns an object that looks like:
{
error: "Login required",
redirect: "/login"
}
I would like to have something that would catch this in the resource, handle it (redirecting to /login), and not pass on to someCB in the controller.
Is there a way to do this with $resource?
Upvotes: 0
Views: 690
Reputation: 6943
It looks like I just needed to do the following:
service('PortfolioService', ['$resource', function($resource) {
return $resource('/api/', {}, {
stock_positions: {
method: 'GET',
url: '/api/stock_positions',
isArray: false,
interceptor:{
response:function(response){
//do stuff here to catch the response before passing it on.
return response;
},
responseError: function(rejection){
console.log(rejection);
}
}
}
});
}]).
Upvotes: 0
Reputation: 1243
I think this can be achieved by angular interceptor.
https://docs.angularjs.org/api/ng/service/$http
$httpProvider.interceptors.push(['$location', function($location) {
return {
'response': function(response) {
if(response.redirect.indexOf('/login'){
// redirect to login
}
return response;
}
};
}]);
Upvotes: 3