Localstorage service angular
ts
import { DOCUMENT } from '@angular/common';
import { inject, Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class LocalstorageService {
private readonly _storage = inject(DOCUMENT)?.defaultView?.localStorage;
get<T>(key: string): T | null {
if (!this._storage) {
return null;
}
return JSON.parse(this._storage.getItem(key) || 'null');
}
set<T>(key: string, value: T) {
if (!this._storage) {
return;
}
this._storage.setItem(key, JSON.stringify(value));
}
clear() {
if (!this._storage) {
return;
}
this._storage.clear();
}
}