angular 12 service for create update delete local storage items
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LocalStorageService {
localStorage: Storage;
changes$ = new Subject();
constructor() {
this.localStorage = window.localStorage;
}
get(key: string): any {
if (this.isLocalStorageSupported) {
return JSON.parse(this.localStorage.getItem(key)!);
}
return null;
}
set(key: string, value: any): boolean {
if (this.isLocalStorageSupported) {
this.localStorage.setItem(key, JSON.stringify(value));
this.changes$.next({
type: 'set',
key,
value
});
return true;
}
return false;
}
remove(key: string): boolean {
if (this.isLocalStorageSupported) {
this.localStorage.removeItem(key);
this.changes$.next({
type: 'remove',
key
});
return true;
}
return false;
}
get isLocalStorageSupported(): boolean {
return !!this.localStorage
}
}
use in Component:
import { Component } from '@angular/core';
import { LocalStorageService } from './local-storage.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
localStorageChanges$ = this.localStorageService.changes$;
constructor(private localStorageService: LocalStorageService) {}
persist(key: string, value: any) {
this.localStorageService.set(key, value);
}
}