Search code examples
angularobservablengrxselectorstore

ngrx observable data took from a ngrx selector is NOT getting updated outside subscribe if the value in REDUX is getting updated from other component


i have an below in my typescript (simplified component) file

public param_getting_updated_inHTML: number = 0;
public param_NOT_getting_updated_inHTML: number = 0;

ngOnInit(): void {
      this.store.select(selectorName).subscribe(
      (data) => { 
        this.param_getting_updated_inHTML= data;
      }
    );

    this.param_NOT_getting_updated_inHTML= this.param_getting_updated_inHTML+ 100;
}

and my (simplified) HTML is as below

<div> {{param_getting_updated_inHTML}}  </div> // this is getting updated properly if the value is changed from other place
<div> {{param_NOT_getting_updated_inHTML}}  </div> // (err) This is not getting updated 

Solution

  • The line

    this.param_NOT_getting_updated_inHTML = this.param_getting_updated_inHTML+ 100;
    

    is outside of the subscription that changes the param_getting_updated_inHTML var, so it will certainly be triggered before the subscription returns the value and updates the param_getting_updated_inHTML var. Thus, since the both vars are initialized with value of 0, the param_NOT_getting_updated_inHTML will just add 100 to 0, while the template will display param_getting_updated_inHTML as some value other than 0 as soon as the subscription returns.

    In other words, if you put

    this.param_NOT_getting_updated_inHTML = this.param_getting_updated_inHTML+ 100;
    

    under the subscription - when param_getting_updated_inHTML actually gets its value from the store - it will work as expected.