0

I want to make a angularJS interceptor that when the client is offline returns instead of an error a cached response as if it wasn't any error.

What I've done so far was to make an interceptor that caches the api requests:

app.factory('httpCachingInterceptor', function ($q, apiCache) {
return {

  'response' : function(response) {
    // cache the api
    if (response.config.url.indexOf('api/') > 0)
      apiCache.addApiCache(response.config.url, response.data);
    return response;
  },

  'responseError' : function(rejection) {
    if (rejection.status == -1) {
      // get the data from apiCache
      // 
      apiCache.getApiCache(rejection.config.url, function(data) {
        // build a new promise and return it as a valid response

      })
    }
    return $q.reject(rejection);
  }

 }
})

I've noticed that when offline the rejection.status is -1 so that's when I check if a request was made while offline.

My question is how I build the response? Should I make a new promise or can I update the rejection?

exilonX
  • 1,712
  • 3
  • 26
  • 50

2 Answers2

0

To convert a rejected promise to a fulfilled promise return a value in the onRejection handler.

Conversely, to convert a fulfilled promise to a rejected promise throw a value in the onFulfilled handler.

For more information, see Angular execution order with $q

Community
  • 1
  • 1
georgeawg
  • 48,608
  • 13
  • 72
  • 95
0

I managed to make it work like this:

'responseError' : function(rejection) {
    if (rejection.status == -1) {
      // get the data from apiCache
      var deferred = $q.defer();

      apiCache.getApiCache(rejection.config.url, function(err, data) {
        if (err || !data) {
          return deferred.reject(rejection);
        }
        rejection.data = data;
        rejection.status = 200;
        deferred.resolve(rejection);
        console.log("Resolve promise with ", rejection);
      })

      return deferred.promise;
    }
    return $q.reject(rejection);
 }

So i made a new promise and modified the rejection I got with the new data from the cache.

exilonX
  • 1,712
  • 3
  • 26
  • 50