In Angular 2+, you can trigger an Observable on localStorage changes using the StorageEvent and BehaviorSubject.
Solution:
Create a Service to Watch localStorage Changes
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class StorageService {
private storageSub = new BehaviorSubject<string | null>(localStorage.getItem('key'));
get storageChanges$() {
return this.storageSub.asObservable();
}
setItem(key: string, value: string) {
localStorage.setItem(key, value);
this.storageSub.next(value);
}
}
Listen for Storage Changes in Another Component
import { Component, HostListener } from '@angular/core';
import { StorageService } from './storage.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
constructor(private storageService: StorageService) {
this.storageService.storageChanges$.subscribe(value => {
console.log('Storage Updated:', value);
});
}
@HostListener('window:storage', ['$event'])
onStorageEvent(event: StorageEvent) {
if (event.key === 'key') {
this.storageService.storageChanges$.subscribe(value => console.log('Updated Value:', value));
}
}
}