简体   繁体   中英

AngularJS: loading an url cached or uncached

I have an AngularJS function, that loads data from a webservice and then stores it in the localStorage. After calling this function the first time, the data should be loaded from localStorage (unless the cache is invalid after an hour).

I would like to externalize this function, but I'm scratching my head, how to put a sync and an async call into one method. Here we go.

function callWebService(url) {
    var resultFromLocalStorage = localStorage.getItem(url);
    if (resultFromLocalStorage && Utils.cacheIsStillValid()) { //(*)
        $timeout(function() { buildTable(JSON.parse(resultFromLocalStorage)); }, 10);
    } else {
        $resource(url).get().$promise.then(function(result) {
            localStorage.setItem("cacheExpiry", new Date().getTime() + Utils.ONE_HOUR_IN_MS);
            localStorage.setItem(url, JSON.stringify(result));
            buildTable(result);
        });
    }
}
//*Utils.cacheIsStillValid checks the localStorage item "cacheExpiry"

I would like to externalize that caching stuff, so in the end, I just want this:

function callWebService(url) {
    var result = getResultFromCacheOrReload(url); // to be done
    buildTable(result);
}

How can I do this? How would the method getResultFromCacheOrReload(url) look?

Thanks, Bernhard

Simply return a promise from getResultFromCacheOrReload and build the table when it is resolved:

function callWebService(url) {
    var result = getResultFromCacheOrReload(url).then(function (result) {
        buildTable(result);
    });
}

The function getResultFromCacheOrReload can be something like:

function getResultFromCacheOrReload(url) {
    var resultFromLocalStorage = localStorage.getItem(url);
    if (resultFromLocalStorage && Utils.cacheIsStillValid()) {
        return $q.when(resultFromLocalStorage); // Create a fulfilled promise containing  resultFromLocalStorage
    } else {
        return $resource(url).get().then(function (result) { // Return the promise returned by the "then" method
            localStorage.setItem("cacheExpiry", new Date().getTime() + Utils.ONE_HOUR_IN_MS);
            localStorage.setItem(url, JSON.stringify(result));
            return result; // Every object returned by a then() method is wrapped by a promise
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM