Search code examples
angulartypescriptngrx-store

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.


Solution

  • 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.