npm install --save ng-localstorage
import { NgLocalStorage } from 'ng-localstorage';
And inject the service
to the constructor:
constructor (private storage: NgLocalStorage) { ...
Lastly, don't forget to declare it into your app.module
or in the providers
section of your component.
providers: [ NgLocalStorage ]
And you can use all localStorage APIs: set, get, remove, clear.
ng-localstorage automatically converts Object
input to JSON
string and save it.
var userData = { name: 'John Doe', email: 'johndoe@mail.com' };
this.storage.set('user', userData);
ng-localstorage allows you to retrieve saved items in Object
format, which means you can use a dot-notation
approach to access Object
properties.
// given that userData Object has been saved in localStorage
this.storage.get('user'); // returns {name: 'John Doe', email: 'johndoe@mail.com'}
this.storage.get('user.name'); // returns 'John Doe'
Same as native localStorage
API approach.
this.storage.remove('user'); // removes the item `user` in the localStorage list
this.storage.clear(); // clears localStorage