How to add call back for $resource methods in AngularJS
Actions from the Resource class can be passed success and error callbacks just like the lower level $http service
- HTTP GET "class" actions: Resource.action([parameters], [success], [error])
- non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
Non-get actions are prefixed with $
.
So you can do this
User.get({userId:123}, function(u, getResponseHeaders){ // this is get's success callback u.abc = true; u.$save(function(u, putResponseHeaders) { // This is $save's success callback, invoke notification from here });});
Edit: here's another example from a previous plunker. The get request will fail since it request a non existing json file. The error callback will be run.
someResource.get(function(data){ console.log('success, got data: ', data); }, function(err){ alert('request failed');});
With latest AngularJS versions, you could have a look to the $interceptors
which are part of the $httpProvider
.
Then you can intercept ALL the requests before beeing sent or after the response.
angular.module('app').config(function($httpProvider){ $httpProvider.interceptors.push(function($q) { return { 'request': function(config) { console.log('I will send a request to the server'); return config; }, 'response': function(response) { // called if HTTP CODE = 2xx console.log('I got a sucessfull response from server'); return response; } 'responseError': function(rejection) { // called if HTTP CODE != 2xx console.log('I got an error from server'); return $q.reject(rejection); } }; });});
Note that you have to return config
or response
to get it working.
In the case of rejection
, you need to return a deferred rejection, to get the $http.get().error()
still working after the interception.