Deukalion
Deukalion

Reputation: 2665

Cordova/AngularJS $http.get always cached

Checking server message when an app is opened every time.

On Android this message is always cached. When the server is offline a cached message is returned. Which also is a problem because then for certain a message should be shown (default error message or a timeout).

Have tried the following:

$http.get(url, { cache: false }) ...

And before

$cacheFactory.get('$http').removeAll();

Even

localStorage.clear();

Also in module index:

.config(['$httpProvider', function($httpProvider)
{
    if (!$httpProvider.defaults.headers.get)
    {
        $httpProvider.defaults.headers.get = {};
    }
}])

On IOS the value does not seem cached instead, except for when the server is offline.

Upvotes: 3

Views: 543

Answers (1)

Gui
Gui

Reputation: 9813

You can either install a Cordova plugin to disable the cache for Android and IOS:

ionic cordova plugin add cordova-disable-http-cache

Or you can check this solution at the ionic forum.

myApp.factory('httpInterceptor', ['$q',function($q) {
var regex = new RegExp('\.(html|js|css)$','i');
var isAsset = function(url){
    return regex.test(url);
};
return {
    // optional method
    'request': function(config) {
        // do something on success
        if(!isAsset(config.url)){            //if the call is not for an asset file
            config.url+= "?ts=" +  Date.now();     //append the timestamp
        }
        return config;
    },

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



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

    // optional method
    'responseError': function(rejection) {
        return $q.reject(rejection);
    }
};
}]);

//appended the interceptor in the config block using $httpProvider
$httpProvider.interceptors.push('httpInterceptor');

Upvotes: 1

Related Questions