【问题标题】:Caching json response from server and automatically detect when the data is changed缓存来自服务器的 json 响应并自动检测数据何时更改
【发布时间】:2014-11-09 18:13:08
【问题描述】:

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

尝试的方法:

1) 我尝试使用 html5 localSorage 将数据保存在本地。但是,这样做的问题是,我应该手动设置过期时间,并且无法知道数据的更改频率。

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

我正在寻找的解决方案,

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

这有可能吗?

【问题讨论】:

    标签: json angularjs caching local-storage cachefactory


    【解决方案1】:

    我希望您从 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();
        }
    

    【讨论】:

    • 嗨,我已经提到过,我确实尝试过使用 localStorage。您假设如果有新用户登录,那么我应该更改存储的数据。然而,事实并非如此,我得到的数据在用户之间是通用的,当发生变化时,所有用户都会发生变化。
    猜你喜欢
    • 1970-01-01
    • 2012-10-19
    • 2018-09-02
    • 2011-01-21
    • 2020-09-21
    • 2012-04-03
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    相关资源
    最近更新 更多