2017-09-06 48 views
0

我在LocalStorage和ngOnInit鉤子中存儲了一些對象我將這些數據接收到數組中,該數組使用* ngFor在模板中顯示。我如何監視LocalStorage中的更改並自動更新視圖?監視LocalStorage中的更改angular2

回答

2

你想要的是一個主題。看看這裏的文檔(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 
}) 

} 
+0

最終該方案比我的清潔劑,如果你能在使用localStorage的通過此服務這樣做的一切算。不過你確實有一些代碼問題。主題的類型是布爾型的,但是您將字符串傳遞給next(),並且由於您正在傳遞字符串,因此它可能是更改項目的關鍵字。此外,可以設置一個可能與存儲中已有內容相匹配的項目,因此任何內容都不應該改變,但是OP可以根據需要實現該細節級別。 –

+0

非常感謝。完美的作品 – Hubert