typescript 从 Angular2 访问 HTML5 本地存储

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39267658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:48:37  来源:igfitidea点击:

Access HTML5 local storage from Angular2

javascripthtmlangulartypescriptlocal-storage

提问by Daniel Stradowski

I'm following this tutorial: https://medium.com/@blacksonic86/authentication-in-angular-2-958052c64492about authentication in Angular2.

我正在关注本教程:https: //medium.com/@blacksonic86/authentication-in-angular-2-958052c64492 关于 Angular2 中的身份验证。

I've the issue with this part:

我有这部分的问题:

import localStorage from 'localStorage';

import localStorage from 'localStorage';

I've read somewhere else that I should use this library https://github.com/marcj/angular2-localstorageto access local storage in HTML5. Is it really the only option? Can I access HTML5 local storage from angular2 without using extra modules?

我在其他地方读过我应该使用这个库https://github.com/marcj/angular2-localstorage来访问 HTML5 中的本地存储。真的是唯一的选择吗?我可以在不使用额外模块的情况下从 angular2 访问 HTML5 本地存储吗?

采纳答案by ranakrunal9

You can use localStoragedirectly in your service without import localStorage from 'localStorage';.

您可以localStorage直接在您的服务中使用,无需import localStorage from 'localStorage';.

回答by GibboK

You should use directly localStorage, as mentioned by other here, it is a builtin browser features (supported browser).

你应该直接使用localStorage,正如这里其他人提到的,它是一个内置的浏览器功能(支持的浏览器)。

Additionally I am adding below few examples on how to add an entry in it (they work both in the same way).

另外,我在下面添加了几个关于如何在其中添加条目的示例(它们的工作方式相同)。

localStorage.colorSetting = '#a4509b';    // dot notation
localStorage['colorSetting'] = '#a4509b'; // bracket notation
localStorage.setItem('colorSetting', '#a4509b');

As a note, angular2-localstorageworks on top of native localStorageand provide a "convenient" way to save and restore automatically a variable state in your directive.

请注意,angular2-localstorage在本机之上工作localStorage并提供一种“方便”的方式来自动保存和恢复指令中的变量状态。

回答by Winnemucca

I noticed that the local storage project is seeking someone to takeover and is not currently being maintained. So I am not going to use it until then. I was able to find the a fix in my tsconfig.jsonfile.

我注意到本地存储项目正在寻找某人接管并且目前没有维护。所以在那之前我不会使用它。我能够在我的tsconfig.json文件中找到修复程序。

In the property lib you can simply add dom

在属性库中,您可以简单地添加dom

"lib": [
      "es2016",
      "dom"
    ]

This is supported in the compiler options https://www.typescriptlang.org/docs/handbook/compiler-options.html.

这在编译器选项https://www.typescriptlang.org/docs/handbook/compiler-options.html 中受支持。

I had to restart visual studio code for this to remove the errors.

我不得不为此重新启动 Visual Studio 代码以消除错误。