30

It could be a common case that we need to show an error/success message to the user after he updates/creates some data, how can we implement it in AngularJS?
I want to add callbacks but could not find a solution. Using $http.post().success().error() works, but I wonder if I can do it with the higher lever API $resource.
Or, we should write directives or use $watch()?
Thanks for your help in advance.

Edward
  • 939
  • 3
  • 10
  • 17

2 Answers2

51

Actions from the Resource class can be passed success and error callbacks just like the lower level $http service

From the docs

  • 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');
});
Dan Brandt
  • 605
  • 1
  • 7
  • 21
jaime
  • 41,961
  • 10
  • 82
  • 52
  • Many thanks! The further question is how to wrap the data into form data? the solution in [this post](http://stackoverflow.com/questions/12190166/angularjs-any-way-for-http-post-to-send-request-parameters-instead-of-json) seems does not work for Resource methods(can work for $http.put). thanks – Edward Dec 13 '12 at 06:11
  • comment = Comment.save($scope.newComment, (response) -> console.log("Comment submitted.")) ...works too. – mikeborgh Oct 05 '13 at 05:41
  • The format for non-get actions is Resource.action([parameters], postData, [success], [error]) .. But in your example it is different u.$save(function(u, putResponseHeaders) {........... – Aakash Apr 24 '14 at 06:42
5

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.

M'sieur Toph'
  • 2,534
  • 1
  • 21
  • 34