gpt4 book ai didi

angular - 观察 LocalStorage angular2 的变化

转载 作者:太空狗 更新时间:2023-10-29 17:29:48 27 4
gpt4 key购买 nike

我将一些对象存储在 LocalStorage 和 ngOnInit Hook 中,我将这些数据接收到我使用 *ngFor 在模板中显示的数组。如何观察 LocalStorage 中的变化并自动更新 View ?

最佳答案

你想要的是一个主题。在此处查看文档 ( https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/subjects/subject.md )

For a quick example, something like this:
@Injectable()
export class StorageService {
...
private storageSub= new Subject<String>();
...

watchStorage(): Observable<any> {
return this.storageSub.asObservable();
}

setItem(key: string, data: any) {
localStorage.setItem(key, data);
this.storageSub.next('changed');
}

removeItem(key) {
localStorage.removeItem(key);
this.storageSub.next('changed');
}
}

Inside Component

constructor(private storageService: StorageService ){}
ngOnInit() {
this.storageService.watchStorage().subscribe((data:string) => {
// this will call whenever your localStorage data changes
// use localStorage code here and set your data here for ngFor
})

}

关于angular - 观察 LocalStorage angular2 的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46078714/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com