0
LocalStorageとngOnInitフックにいくつかのオブジェクトを保存しましたが、このデータを* ngForでテンプレートに表示する配列に受け取ります。 LocalStorageの変更を監視し、自動的にビューを更新するにはどうしたらいいですか?LocalStorage angular2の変更を監視する
LocalStorageとngOnInitフックにいくつかのオブジェクトを保存しましたが、このデータを* ngForでテンプレートに表示する配列に受け取ります。 LocalStorageの変更を監視し、自動的にビューを更新するにはどうしたらいいですか?LocalStorage angular2の変更を監視する
あなたは何をしたいですか?あなたはのlocalStorageは、本サービスを通じてそう使用するすべてのものに数えることができるならば、ここでのドキュメントをチェックアウト(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<boolean>();
...
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
})
}
は最終的に、このソリューションは私よりもきれいです。あなたはいくつかのコードの問題があります。件名の型はブールですが、文字列をnext()に渡しています。文字列を渡すので、変更された項目のキーでもよいでしょう。また、既に何が変更されているはずなので、OP内に保存されているものと一致する可能性のある項目が設定されていてもかまいません。 –
ありがとうございました。完璧に動作します – Hubert