本地存储在应用程序初始化中不起作用

Localstorage not working in app initialization

我有下面的代码

angular
.module('core')
.factory('jsonstorage',function($rootScope,$http,$localStorage){

     return {
        set: function(entidy, value) {
           $rootScope.$storage = $localStorage;
            $rootScope.$storage[entidy] = value;

        },
        get: function(entidy) {
          if (typeof $rootScope.$storage != 'undefined') {
            return $rootScope.$storage[entidy];
          }
        }
    } 


});

控制器

angular
.module('core')
.controller('HomeController', function($scope,$http,$rootScope,$localStorage,jsonstorage) {
  var url = "http://test.com/?feed=xml";
  $http.get(
  url,
  {transformResponse:function(data) {
  // convert the data to JSON and provide
  // it to the success function below
    var x2js = new X2JS();
    var json = x2js.xml_str2json( data );
    return json;
  }
  }).
  success(function(data, status, headers, config) {
     jsonstorage.set('eventlist', data.feed.events.event);
  }).
  error(function(data, status, headers, config) {
      console.error('Error fetching feed:', data);
  }); 

$scope.feed.items =  $rootScope.storage['eventlist']


console.log(jsonstorage.get('eventlist'))

console.log($scope.storage['eventlist']);
});

问题:

在 android 设备上安装应用程序时,存储 return 未定义的值。但是当我通过 chrome://inspect/#devices 重新加载应用程序时,所有数据反馈都会加载回来。

我对 chrome 桌面浏览器没有问题。

当我删除应用程序并在设备中重新初始化它时,它总是发生

感谢任何帮助

谢谢

每次您删除应用程序时,本地存储也会随之删除。无法在应用程序删除之间保留数据。

此外,您正在进行的 AJAX 调用是一个异步调用,您必须在 .success() 方法中初始化您的 $scope.feeds.items,如下所示:

angular.module('core')controller('HomeController',
   function($scope,$http,$rootScope,$localStorage,jsonstorage) {
     var url = "http://test.com/?feed=xml";
     $http.get(url, {transformResponse:function(data) {
      var x2js = new X2JS();
      var json = x2js.xml_str2json( data );
      return json;
   }
 }).
 success(function(data, status, headers, config) {
   jsonstorage.set('eventlist', data.feed.events.event);
   $scope.feed.items =  $rootScope.storage['eventlist'];
   console.log(jsonstorage.get('eventlist'))
   console.log($scope.storage['eventlist']);
 }).
 error(function(data, status, headers, config) {
  console.error('Error fetching feed:', data);
 }); 
 });

此外,当您刷新页面时,您的代码正在运行,因为到那时,您的第一个 AJAX 调用的响应已返回,因此您的 $scope.feeds.items 已初始化。