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');
}
}