TypeError: Cannot set property of null while using local storage

TypeError: Cannot set property of null while using local storage

在引入本地存储之前,我的代码一直运行良好。我所做的是:当设备准备就绪时检查值是否存在,如果存在则获取它们。在函数的主体中,我为该变量范围分配了一个值,这就是我收到此错误的地方。

$ionicPlatform.ready(function() {
if (localStorageService.get("modelTrue") == null) {
  $scope.userModal.show();
  localStorageService.set("modelTrue", "true")
}
else {
  //Parameter to restore:
  if(localStorageService.get("first") != null){
    $scope.data.firstDisplay = JSON.parse(localStorageService.get("first"));
  }
}; 
$scope.scanBarcode = function() {
                 $scope.data.firstDisplay = {'src' : 'img/1.png'}; //this is where I get the error
                 localStorageService.set("first", JSON.stringify($scope.data.firstDisplay));   
              }

当我调用最后一个函数时出现错误:"TypeError: Cannot set property 'firstDisplay' of null"。

我不明白这种行为。我只是将一个变量设置为一个值。 这可能意味着什么?

空值来自console.log($scope.data);

您需要申报$scope.data ={};否则它总是空的,

$ionicPlatform.ready(function() {
            $scope.data ={};
            if (localStorageService.get("modelTrue") == null) {
                $scope.userModal.show();
                localStorageService.set("modelTrue", "true")
            } else {
                //Parameter to restore:
                if (localStorageService.get("first") != null) {
                    $scope.data.firstDisplay = JSON.parse(localStorageService.get("first"));
                }
            };
            $scope.scanBarcode = function() {
                $scope.data.firstDisplay = {
                    'src': 'img/1.png'
                }; //this is where I get the error
                localStorageService.set("first", JSON.stringify($scope.data.firstDisplay));
            }