Access HTML5 local storage from Angular2

10,587

Solution 1

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

Solution 2

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.

Solution 3

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.

Share:
10,587
Daniel Stradowski
Author by

Daniel Stradowski

Updated on July 18, 2022

Comments

  • Daniel Stradowski
    Daniel Stradowski almost 2 years

    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?

  • Daniel Stradowski
    Daniel Stradowski over 7 years
    sounds awesome. Than I guess this import localStorage in unnecessary in the tutorial and is simply a mistake?
  • ranakrunal9
    ranakrunal9 over 7 years
    yes, i have already used localStorage directly in one of my service.
  • stijn.aerts
    stijn.aerts over 7 years
    @ranakrunal9 how did this work out with the testing? Did it work okay?
  • mark.sagikazar
    mark.sagikazar over 7 years
    The alternative is to introduce a storage interface and unit test with a mock implementation I guess.
  • Winnemucca
    Winnemucca about 7 years
    how did you manage the error handling with typescript? 'Cannot find name 'localStorage'.