简体   繁体   中英

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.

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.

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

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. We also must unsubscribe to release the hook when not in use to avoid unnecessary usage of memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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