How to use Local storage in Angular [duplicate]
The standard localStorage
API should be available, just do e.g.:
localStorage.setItem('whatever', 'something');
It's pretty widely supported.
Note that you will need to add "dom"
to the "lib"
array in your tsconfig.json
if you don't already have it.
How to store, retrieve & delete data from localStorage:
// General syntax for storing data
localStorage.setItem('key', 'value');
// Also note that both the key & the value has to be strings.
// So we stringify the value(if it's an object) before setting it.
// So, if you have an object that you want to save, stringify it like this
let data = {
'token': 'token',
'name': 'name'
};
localStorage.setItem('myLSkey', JSON.stringify(data));
// OR for individual key-value pairs
localStorage.setItem('myLSkey', JSON.stringify({
'token': 'token',
'name': 'name'
}));
// To retrieve the data & save it to an existing variable
data = JSON.parse(localStorage.getItem('myLSkey'));
// To remove a value/item from localStorage
localStorage.removeItem("myLSkey");
Tips:
You can also use a package for your angular app, that is based on native localStorage API (that we are using above) to achieve this and you don't have to worry about stringify and parse. Check out this package for angular 5 and above. @ngx-pwa/local-storage
You can also do a quick google search for maybe,angular local storage, & find a package that has even more Github stars etc.
Check out this page to know more about Web Storage API.
Save into LocalStorage:
localStorage.setItem('key', value);
For objects with properties:
localStorage.setItem('key', JSON.stringify(object));
Get From Local Storage:
localStorage.getItem('key');
For objects:
JSON.parse(localStorage.getItem('key'));
localStorage Object will save data as string and retrieve as string. You need to Parse desired output
if value is object stored as string.
e.g. parseInt(localStorage.getItem('key'));
It is better to use framework provided localStroage instead of 3rd party library localStorageService or anything else because it reduces your project size.
Here is an example of a simple service, that uses localStorage to persist data:
import { Injectable } from '@angular/core';
@Injectable()
export class PersistanceService {
constructor() {}
set(key: string, data: any): void {
try {
localStorage.setItem(key, JSON.stringify(data));
} catch (e) {
console.error('Error saving to localStorage', e);
}
}
get(key: string) {
try {
return JSON.parse(localStorage.getItem(key));
} catch (e) {
console.error('Error getting data from localStorage', e);
return null;
}
}
}
To use this services, provide it in some module in your app like normal, for example in core module. Then use like this:
import { Injectable } from '@angular/core';
@Injectable()
export class SomeOtherService {
constructor(private persister: PersistanceService) {}
someMethod() {
const myData = {foo: 'bar'};
persister.set('SOME_KEY', myData);
}
someOtherMethod() {
const myData = persister.get('SOME_KEY');
}
}
Use Angular2 @LocalStorage module, which is described as:
This little Angular2/typescript decorator makes it super easy to save and restore automatically a variable state in your directive (class property) using HTML5' LocalStorage.
If you need to use cookies, you should take a look at: https://www.npmjs.com/package/angular2-cookie