lakshay lakshay - 18 days ago 7
AngularJS Question

How to update angular localstorage service after period of 7 days?

I am setting data into my

LocalStoargeService
from an Api request response

WishListService.getWishListTags(function(response) {
var WISHLIST_TAGS_STORAGE_KEY = 'wishlist_tags';
localStorageService.set(WISHLIST_TAGS_STORAGE_KEY, response.data);
});


Now I want to update this data in the LocalStorageService after period of 7 days from the same Api request.

Answer

When you call an api set a new call time. And check that time in your service. If time is behind, call that service again and set new time.

You can use $promise for that kind of calls. Here is a simple example for you. You can call callWishList whenever you want whish_list.

function updateWishList(response){
    var WISHLIST_TAGS_STORAGE_KEY = 'wishlist_tags';
    localStorageService.set(WISHLIST_TAGS_STORAGE_KEY, response.data);
}

function getWishList(){
    var WISHLIST_TAGS_STORAGE_KEY = 'wishlist_tags';
    return localStorageService.get(WISHLIST_TAGS_STORAGE_KEY);
}

function callWishList(){
    var deferred = $q.defer();
    //check last update time
    //last_update is a date
    var last_update = localStorageService.get("wish_list_update_date");
    var now_date = new Date();
    if(now_date.getTime()>last_update.getTime()){
        //this means you need to update your data and last_update
        $http.post("myWishListFromServerURL", {})
                .success(function (response) {
                    localStorageService.set("wish_list_update_date",new Date());
                    updateWishList(response);
                    deferred.resolve(response);
                })
                .error(function (response) {
                    deferred.reject(response);
                });
    }else{
        deferred.resolve(getWishList());
    }
    return deferred.promise;
}