showing results for - "angular 12 service for create update delete local storage items"
Joshua
11 Oct 2019
1import { Injectable } from '@angular/core';
2import { Subject } from 'rxjs';
3@Injectable({
4  providedIn: 'root'
5})
6export class LocalStorageService {
7  localStorage: Storage;
8  changes$ = new Subject();
9  constructor() {
10    this.localStorage   = window.localStorage;
11  }
12  get(key: string): any {
13    if (this.isLocalStorageSupported) {
14      return JSON.parse(this.localStorage.getItem(key)!);
15    }
16    return null;
17  }
18  set(key: string, value: any): boolean {
19    if (this.isLocalStorageSupported) {
20      this.localStorage.setItem(key, JSON.stringify(value));
21      this.changes$.next({
22        type: 'set',
23        key,
24        value
25      });
26      return true;
27    }
28    return false;
29  }
30  remove(key: string): boolean {
31    if (this.isLocalStorageSupported) {
32      this.localStorage.removeItem(key);
33      this.changes$.next({
34        type: 'remove',
35        key
36      });
37      return true;
38    }
39    return false;
40  }
41  get isLocalStorageSupported(): boolean {
42    return !!this.localStorage
43  }
44}
45
46use in Component:
47
48import { Component } from '@angular/core';
49import { LocalStorageService } from './local-storage.service';
50@Component({
51  selector: 'app-root',
52  templateUrl: './app.component.html',
53  styleUrls: ['./app.component.css']
54})
55export class AppComponent {
56  localStorageChanges$ = this.localStorageService.changes$;
57  constructor(private localStorageService: LocalStorageService) {}
58  persist(key: string, value: any) {
59    this.localStorageService.set(key, value);
60  }
61}