在angularjs中,当localStorage已满时,如何捕获ngStorage的错误?

时间:2015-06-11 22:14:57

标签: javascript html angularjs local-storage ng-storage

我在AngularJS中使用localStorage将几个项目保存到ngStorage,但如果用户的localStorage已满,我怎样才能捕获该错误并允许JavaScript保留运行

try {  
    $scope.$storage.gridObject = $scope.gridConfig.data;  
    $scope.$storage.dataStored=true; 
}  
catch(err) {  
    //failed to save to local storage,  try clearing localStorage for IAP and throw error  
    $scope.$storage.dataStored=false;  
    $scope.$storage.$reset({    
        dataStored: false,
        gridObject: {}  
    })  
    console.log('error occured message');  
}

1 个答案:

答案 0 :(得分:0)

也许并非针对AngularJS,您应该能够通过以下内容获得localStorage的详细信息。

var allocated = 5; // default 5MB allocation
var total = 0;
for(var x in localStorage) {  
    var amount = (localStorage[x].length * 2) / 1024 / 1024;  
    total += amount;  
}
var remaining = allocated - total;
console.log( 'Used: ' + total + ' MB');
console.log( 'Remaining: ' + remaining + ' MB');

JSFiddle Link - 演示

有关异常驱动的方法,请参阅this answer。引用的答案将分享如何强制您可能捕获的异常。如果您的电量不足,上面的代码可能允许您执行/绕过某些逻辑。