最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Access HTML5 local storage from Angular2 - Stack Overflow

programmeradmin2浏览0评论

I'm following this tutorial: /@blacksonic86/authentication-in-angular-2-958052c64492 about authentication in Angular2.

I've the issue with this part:

import localStorage from 'localStorage';

I've read somewhere else that I should use this library to access local storage in HTML5. Is it really the only option? Can I access HTML5 local storage from angular2 without using extra modules?

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

I've the issue with this part:

import localStorage from 'localStorage';

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

Share Improve this question edited Jan 10, 2017 at 14:40 GibboK 73.9k147 gold badges451 silver badges672 bronze badges asked Sep 1, 2016 at 9:24 Daniel StradowskiDaniel Stradowski 3,4841 gold badge14 silver badges22 bronze badges 1
  • 2 You do not need to import anything, localStorage is a builtin browser feature and it's part of the lib.d.ts. – Nitzan Tomer Commented Sep 1, 2016 at 9:27
Add a comment  | 

3 Answers 3

Reset to default 9

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

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

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-localstorage works on top of native localStorage and provide a "convenient" way to save and restore automatically a variable state in your directive.

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.json file.

In the property lib you can simply add dom

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

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

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

发布评论

评论列表(0)

  1. 暂无评论