简体   繁体   English

如何从角度组件中的ngrx商店获取东西

[英]How to get stuff from ngrx store in an angular component

I have this piece of code inside the component: 我在组件中有这段代码:

    ngDoCheck(){
    this.store.select('info').pipe(map((val: Info) => {
        window.alert(val.user.name);
        this.user.name = val.user.name;
    }));
}

First i would like to verify that this doesn't subscribe to the observable and instead checks the value asynchronously like i thought. 首先,我想验证这不会订阅observable,而是像我想的那样异步地检查值。

Second i would like to know why its not working, using the debugger i see that val is undefined but the store has the property stored so the property is stored in the store but this code doesn't reach it. 其次我想知道它为什么不工作,使用调试器我看到val是未定义的但是商店存储了属性,因此属性存储在商店中但是这个代码没有到达它。

I also see that the code inside map is never reached. 我也看到地图中的代码永远不会到达。 Thanks. 谢谢。 Any help is appreciated. 任何帮助表示赞赏。 Have a good day. 祝你有美好的一天。

You need to subscribe to be able to listen to the state changes, and you don't need to force typing , cause if you typed properly the "InfoState" the ts inheritance will give you the right type inside the subscribe 您需要订阅才能听取状态更改,并且您不需要强制键入,因为如果您正确键入“InfoState”,ts继承将在订阅中为您提供正确的类型

this.store.select('info').subscribe(info => {
    window.alert(info.user.name);
    this.user.name = info.user.name;
});

The standard way is to subscribe to store and unsubscribe when it is done. 标准方法是在完成后订阅存储和取消订阅。

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();
}

By using Subscription , we make sure that store is subscribed to specific slice of it ('info') so any changes in this slice, your component will be notified. 通过使用Subscription ,我们确保商店订阅了它的特定片段('info'),因此该片段中的任何更改都会通知您的组件。 We also must unsubscribe to release the hook when not in use to avoid unnecessary usage of memory. 我们还必须取消订阅以在不使用时释放挂钩以避免不必要的内存使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM