Chris
Chris

Reputation: 27384

Intercept $http request and return response without server request

I want to, on certain http requests, return data from memory rather than letting it hit the server. I know I can write http interceptors but I'm not sure how to actually return the response from the request?

myModule.factory('myHttpInterceptor', function ($q) {
    return {
        // optional method
        'request': function (config) {
            // return my data here [200], and stop the call from going through
            return config;
        }
    };
});

Upvotes: 4

Views: 1173

Answers (2)

Nikolaj Dam Larsen
Nikolaj Dam Larsen

Reputation: 5674

Here's a solution that only uses interceptors. I'd still argue Érics solution in the comments is more elegant, but now you have different options to consider.

app.factory('myHttpInterceptor', function ($q, myCache) {
    return {
        request: function (config) {
            var cached = myCache.getCachedData(config.params);
            if(cached){
                return $q.reject({cachedData: cached, config: config });
            }
            return config;
        },

        response: function(response){
            // myCache.saveData(response.data);
        },

        responseError: function(rejection) {      
            if(rejection.cachedData){
                return $q.resolve(rejection.cachedData);
            }
            return $q.reject(rejection);
        }
    };
});

Upvotes: 6

Matej Marconak
Matej Marconak

Reputation: 1413

You can check this article: Caching HTTP

Or you can use cache parameters for $http (check more in angular documentation):

$http.get('api/path',{
    cache: true
}

Upvotes: 2

Related Questions