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
Local Storage Set Item
Syntax:
localStorage.setItem(key,value);
localStorage.getItem(key);
Example:
localStorage.setItem("name","Muthu");
if(localStorage){ //it checks browser support local storage or not
let Name=localStorage.getItem("name");
if(Name!=null){ // it checks values here or not to the variable
//do some stuff here...
}
}
also you can use
localStorage.setItem("name", JSON.stringify("Muthu"));
Session Storage Set Item
Syntax:
sessionStorage.setItem(key,value);
sessionStorage.getItem(key);
Example:
sessionStorage.setItem("name","Muthu");
if(sessionStorage){ //it checks browser support session storage/not
let Name=sessionStorage.getItem("name");
if(Name!=null){ // it checks values here or not to the variable
//do some stuff here...
}
}
also you can use
sessionStorage.setItem("name", JSON.stringify("Muthu"));
Store and Retrieve data easily
You can also consider using library maintained by me: ngx-store (npm i ngx-store
)
It makes working with localStorage, sessionStorage and cookies incredibly easy. There are a few supported methods to manipulate the data:
1) Decorator:
export class SomeComponent {
@LocalStorage() items: Array<string> = [];
addItem(item: string) {
this.items.push(item);
console.log('current items:', this.items);
// and that's all: parsing and saving is made by the lib in the background
}
}
Variables stored by decorators can be also shared across different classes - there is also @TempStorage()
(with an alias of @SharedStorage()
)) decorator designed for it.
2) Simple service methods:
export class SomeComponent {
constructor(localStorageService: LocalStorageService) {}
public saveSettings(settings: SettingsInterface) {
this.localStorageService.set('settings', settings);
}
public clearStorage() {
this.localStorageService.utility
.forEach((value, key) => console.log('clearing ', key));
this.localStorageService.clear();
}
}
3) Builder pattern:
interface ModuleSettings {
viewType?: string;
notificationsCount: number;
displayName: string;
}
class ModuleService {
constructor(public localStorageService: LocalStorageService) {}
public get settings(): NgxResource<ModuleSettings> {
return this.localStorageService
.load(`userSettings`)
.setPath(`modules`)
.setDefaultValue({}) // we have to set {} as default value, because numeric `moduleId` would create an array
.appendPath(this.moduleId)
.setDefaultValue({});
}
public saveModuleSettings(settings: ModuleSettings) {
this.settings.save(settings);
}
public updateModuleSettings(settings: Partial<ModuleSettings>) {
this.settings.update(settings);
}
}
Another important thing is you can listen for (every) storage changes, e.g. (the code below uses RxJS v5 syntax):
this.localStorageService.observe()
.filter(event => !event.isInternal)
.subscribe((event) => {
// events here are equal like would be in:
// window.addEventListener('storage', (event) => {});
// excluding sessionStorage events
// and event.type will be set to 'localStorage' (instead of 'storage')
});
WebStorageService.observe()
returns a regular Observable, so you can zip, filter, bounce them etc.
I'm always open to hearing suggestions and questions helping me to improve this library and its documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With