Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept $http request and return response without server request

Tags:

http

angularjs

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;
        }
    };
});
like image 669
Chris Avatar asked Sep 13 '25 07:09

Chris


2 Answers

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);
        }
    };
});
like image 198
Nikolaj Dam Larsen Avatar answered Sep 14 '25 22:09

Nikolaj Dam Larsen


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
}
like image 41
Matej Marconak Avatar answered Sep 14 '25 21:09

Matej Marconak