[英]How to get stuff from ngrx store in an angular component
我在組件中有這段代碼:
ngDoCheck(){
this.store.select('info').pipe(map((val: Info) => {
window.alert(val.user.name);
this.user.name = val.user.name;
}));
}
首先,我想驗證這不會訂閱observable,而是像我想的那樣異步地檢查值。
其次我想知道它為什么不工作,使用調試器我看到val是未定義的但是商店存儲了屬性,因此屬性存儲在商店中但是這個代碼沒有到達它。
我也看到地圖中的代碼永遠不會到達。 謝謝。 任何幫助表示贊賞。 祝你有美好的一天。
您需要訂閱才能聽取狀態更改,並且您不需要強制鍵入,因為如果您正確鍵入“InfoState”,ts繼承將在訂閱中為您提供正確的類型
this.store.select('info').subscribe(info => {
window.alert(info.user.name);
this.user.name = info.user.name;
});
標准方法是在完成后訂閱存儲和取消訂閱。
storeSubscription: Subscription;
ngOnInit() {
this.storeSubscription = this.store.select('info').subscribe(info => {
window.alert(info.user.name);
this.user.name = info.user.name;
});
}
ngOnDestroy() {
this.storeSubscription.unsubscribe();
}
通過使用Subscription
,我們確保商店訂閱了它的特定片段('info'),因此該片段中的任何更改都會通知您的組件。 我們還必須取消訂閱以在不使用時釋放掛鈎以避免不必要的內存使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.