LocalStorage service for Angular projects to watch, detect LocalStorage changes
npm install lib-storage-service
In your app.module.ts
(or any module.ts file):
import { LibStorageService } from 'lib-storage-service/dist/lib-storage-service/public-api';
then:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [
LibStorageService
],
bootstrap: [AppComponent]
})
export class AppModule { }
In your components:
import { Component } from '@angular/core';
import { LibStorageService } from 'lib-storage-service/dist/lib-storage-service/public-api';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'my-test-app';
constructor(
storageService: LibStorageService,
) {
storageService.setItem('foo', 'bar');
}
}
Use this method to set item in LocalStorage
and notify observers.
Usage:
storageService.setItem(key, value);
Use this method to remove item from LocalStorage
and notify observers.
Usage:
storageService.removeItem(key);
Use this method to remove all item from LocalStorage
and notify observers.
Usage:
storageService.clear();
Usage:
storageService.watchStorage().subscribe(() => {
// check changes and handle it
});
Detect the token
key changes in LocalStorage
. If token goes to empty we call authService.logout()
method:
storageService.watchStorage().subscribe(() => {
const token = LocalStorage.getItem('token');
if (!token) {
authService.logout();
}
});