ngStorage 和 $window.localStorage 之间的区别

Difference between ngStorage and $window.localStorage

ngStorage 和 $window.localStorage 有什么区别?什么时候用一个比另一个更好? 我必须为网络应用程序选择其中之一。我必须保存配置文件用户的数据和令牌

变量$window通常是全局window变量。 Angular 推荐使用 $window 的原因是因为有时你想模拟或替换 "real" window 对象(例如为了测试目的)。

这么说,using $window.localStorage 意味着你使用的是 Local Storage 的 vanilla API,而 ngStorage 是

An AngularJS module that makes Web Storage working in the Angular Way. Contains two services: $localStorage and $sessionStorage

来源here

这是正常的html5本地存储:

With local storage, web applications can store data locally within the user's browser. Before HTML5, application data had to be stored in cookies, included in every server request. Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance. Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server. Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.

它为您提供访问存储的对象 - window.localStorage 和 window.sessionStorage

window.localStorage - 存储没有有效期的数据

window.sessionStorage - 存储一个会话的数据,因此当浏览器选项卡关闭时数据丢失

要检索数据,您可以这样做

localStorage.getItem("lastname"); 

因此,如果您想在 angular 中执行此操作,您将使用 $window 服务,但它的行为与上述示例相同。

Source


地址 ngStorage:

An AngularJS module that makes Web Storage working in the Angular Way. Contains two services: $localStorage and $sessionStorage. No dealing with getters and setters like you have to in $window service

您可以在 $scope 下通过引用传递 $localStorage 或 $sessionStorage:

$scope.$storage = $localStorage;

然后你可以使用 $storage as 和其他 angular 变量

<body ng-controller="Ctrl">
    <button ng-click="$storage.counter = $storage.counter + 1">{{$storage.counter}}</button>
</body>

Source


如果您将在您的 webapp 中使用 angularjs,我会使用 ngStorage,因为您会更熟悉语法。不过这只是我的意见。

请注意 ngStorage 在内部使用 Angular 监视来监视对 $storage/$localStorage 对象的更改,即需要一个摘要循环才能将新值可靠地保存到浏览器的本地存储。通常这不是问题,但如果您在 $localStorage 中存储一个值并在没有摘要循环发生的情况下打开一个新选项卡,您可能无法在新打开的 tab/window 中看到存储的值。

运行 在 IE 上遇到这个问题,不得不使用 window.localStorage 来解决它。

var setLocalStorage = function (token, uname)
{
$localStorage.token = token;
$localStorage.name = uname;

}
$timeout(setLocalStorage(token, userForm.uname), 500);

Module Used : ngStorage

有效!