Search code examples
angularjsasynchronousinterceptorngresource

ngResource with async response interceptor


I'm writing a response intercepter for an API call with ngResource like this:

var Thing = $resource('/api/things/:id', {id: '@id'}, {
  queryAll: {
    method: 'GET',
    interceptor: {
      response: function(response) {
        var instance = response.resource;

        doAsyncStuffHere(instance.data);

        return instance;
      }
    }
  }
});

The interceptor function should enrich the data from the response but returns the unmodified instance before the async stuff is done (as expected, since it's async...).

Is there a good way, to enrich the data asynchronously and make the return statement "wait" until it's done? Callback? Promise?


Solution

  • After searching the right question, i've found an article who solved my issue:

    Sometimes there is a need to make some asynchronous operations inside the interceptor. Luckily AngularJS allows us to return a promise that will be resolved later. This will defer the request sending in case of request interceptor and will defer the response resolving in case of response interceptor.

    From: http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/

    And here is what my code now looks like and working like a charm.

    var Thing = $resource('/api/things/:id', {id: '@id'}, {
      queryAll: {
        method: 'GET',
        interceptor: {
          response: function(response) {
            var instance  = response.resource,
                _deferred = $q.defer();
    
            doAsyncStuffHere(instance.data).then(function() {
                _deferred.resolve(instance);
            });
    
            return deferred.promise;
          }
        }
      }
    });