Data will disappear after page refresh,

2019-06-11 17:55发布

问题:

Now I am using a service to pass data from view to other view(different controller too), in the view A, I have controller CtrA,for the service I use to pass data is:

.factory(
                'editreportservices',
                [
                        '$q',
                        'sessionId',
                        function($q, sessionId) {
                                var sharedata = {};
                                var org={};
                                function passed(data){
                                    sharedata = data;
                                };
                                function getsharedata(){
                                    return sharedata;
                                };
                                function passedorg(data) {
                                    org=data;
                                }
                                function getorg() {
                                    return org;
                                }
                                return{
                                    passed:passed,
                                    getsharedata:getsharedata,
                                    passedorg:passedorg,
                                    getorg:getorg
                                }               
                        }]);

in the CtrA, if I hit a button, I will set value for editreportservices.passed(report) like:

$scope.goeditpage = function(report){if(report){
                            editreportservices.passed(report);
                            }
                            else{
                            report={}
                            editreportservices.passed(report);
                            };
                       $state.go('editreport');
}

and it will also change to View B, and in VIew B I can access to the data by using $scope.lin = editreportservices.getsharedata(), It works as expect. But there is a problem,I am not sure it is a bug or not,if user refresh page, the data passed from viewA will disappear. it may be a bad user experience, is there anyway I I can keep the data in viewB after It is passed from VIewA?

回答1:

If the user refresh the page, the scripts will load freshly in the browser. So whatever you've saved will be lost.

If you want to persist, then you must store the data either in localStorage or in cookies.

In your service,

var sharedata = localStorage.getItem("shareData")?  JSON.parse(localStorage.getItem("shareData")) || {};
var org={};
function passed(data){
      sharedata = data;
      localStorage.setItem("shareData", JSON.stringify(sharedata));
};
function getsharedata(){
     return sharedata;
};


回答2:

That's not a bug, that's normal. You could put in use HTML5 storage, with expiring storage times.