我在Angular中编写了一个用于管理localstorage状态的服务。
它命名为localStorage.service.ts,providers: [LocalStorageService]
位于app.module.ts
代码就像
observer: Observer<any>;
observable: Observable<any>;
setKey(key, item){
localStorage.setItem(key, item);
observer.next("change");
}
constructor(){
this.observable = new Observable(obs => {
this.observer = obs;
window.addEventListener("storage", event => { obs.next("change") });
});
}
然而,当我在其他组件中订阅它时 例如:a.component.ts
import { Storage } from "localStorage.service";
然后
constructor(private storage:Storage){
storage.subscribe(change => {
console.log("1");
console.log("2");
})
storage.set('test', 'test');
}
预期输出
1
2
// route to other page and back
1
2
实际输出
2
// route to other page and back
2
答案 0 :(得分:0)
我不明白你的代码,抱歉。我想你可以用
您的服务
observer: Subject<any>=new Subject<any>; //<--we create a Subject
observable: this.observer.asObservable();
setKey(key, item){
localStorage.setItem(key, item);
observer.next("change");
//or observer.next(key);
}
constructor(){
//nothing, it's not necesary windows.addEventListener
}
您的组件
constructor(private storage:Storage){}
//In ngOnInit
ngOnInit()
{
//we subscribe to observable
this.storage.observable.subscribe((data:any)=>
{
console.log(data) //output: "change" //or "test"
console.log("1");
console.log("2");
}
storage.setKey('test', 'test'); //<--call to setKey
}