0

With angular $resource, I would like to fire a callback function when a request is successfully sent to the restful backend. (The backend may take a long time and I only want to know if it received the data I sent.)

The only thing I've found so far is resource.action.$promise['finally'](callback);

I'd be also interested to know when the request could not be sent. (eg. connection problems)

Thanks!

Barney Szabolcs
  • 11,846
  • 12
  • 66
  • 91

1 Answers1

1

Here is DRY approach :

Build a service intercepting every HTTP requests (like the one defined in the official documentation) :

   $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
    return {
      // optional method
      'request': function(config) {
        // do something on success
        return config;
      },

      // optional method
     'requestError': function(rejection) {
        // do something on error
        if (canRecover(rejection)) {
          return responseOrNewPromise
        }
        return $q.reject(rejection);
      },



      // optional method
      'response': function(response) {
        // do something on success
        return response;
      },

      // optional method
     'responseError': function(rejection) {
        // do something on error
        if (canRecover(rejection)) {
          return responseOrNewPromise
        }
        return $q.reject(rejection);
      }
    };
  });

Simply put your code inside the desired hooks. You could for instance draw an error modal dialog if the request fails.

Finally, Register it to your application :

app.config(['$httpProvider', function($httpProvider) {
        // Add the interceptor to the $httpProvider to intercept http calls
        $httpProvider.interceptors.push('myHttpInterceptor');

    }]);
Alexandre Nucera
  • 2,183
  • 2
  • 21
  • 34