缓存来自服务器的json响应,并自动检测数据何时更改



我正在开发一个angular应用程序,它可以调用服务器并获取JSON数据。我正在考虑缓存这个JSON数据。

尝试的方法:

1) 我尝试使用html5 localSorage在本地保存数据。但是,问题是,我应该手动设置过期时间,而且无法知道数据偶尔会发生什么变化。

2) 我尝试过使用$cacheFactory,但它不会在刷新或页面导航时缓存数据。

我正在寻找的解决方案,

我希望数据保存在本地或缓存。并使用某种机制来检测服务器返回的数据(JSON数据)是否发生了更改,然后才进行调用。

这有可能吗?

我希望您从html获取数据,调用web服务并将数据存储在本地存储中。在$http中,成功调用将数据存储在本地存储器中的函数。

setUserDetails = function(userData){
var username = "";
if(userData != null){
app.setInLocalStorage("loginName",userData.userName);}
}

其中userData就像一个保存html数据的对象,

var userData= {
 userName : $scope.userName,
 };

从本地存储获取userData.userName

 var userLoggedIn = app.retrieveFromLocalStorage("userName");

比较数据是从服务器更改的还是不是

if(userLoggedIn != null){
            //call the service which gives dynamic response 
            //i hope your saving the success data in userData and userName is property which changes dynamically 
         var newUser = userData.userName;
        if(angular.equals(userLoggedIn, newUser){
             // maintain the same data in localstorage 
                        //or
               //No need to call any other function calls
         }else{    
                  //clear the old data from local storage 
                      app.clearLocalStorage();
                 //storage the new dynamic data in local storage 
                           //or
                  //call the new function calls if you need 
                app.setInLocalStorage("loginName",newUser)
             }
}

在app.js文件中包含以下行以存储、检索、清除本地存储

setInLocalStorage : function(key , value) {
            // Check browser support
            if (typeof(Storage) != "undefined")
            {
                // Store
                localStorage.setItem(key , value);
            }
            else
            {
                alert("Sorry, your browser does not support Web Storage...");
            }
        },
       retrieveFromLocalStorage : function(key){
        return localStorage.getItem(key);
    },
    clearLocalStorage : function(){
        localStorage.clear();
    }

最新更新