Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ngrx/store - why does subscribe method on observable returns previous state?

The problem appears to be beyond me. I have built store correctly and now I can't retrieve current element from the store.

showDialog(id_clicked) {
    this.id = id_clicked
    this.store.dispatch(new action.loadExampleAction(this.id));
    this.observable$ = this.store.select(selectors.getObject);
}

With this simple example I am updating the "observable" whenever button is clicked, dispatching the new action with currently selected id. Showing this.observable$ in the console shows correctly the currently selected object in its payload. But now when I do this:

tmp: <Object> = null
showDialog(id_clicked) {
        this.id = id_clicked
        this.store.dispatch(new action.loadExampleAction(this.id));
        this.observable$ = this.store.select(selectors.getObject);

        this.observable$.subscribe(object => {
        this.tmp = object
        }, first())
        console.log(this.tmp)
}

The tmp inside subscribe returns previous state. I.e. if I click the object with id = 1 at first it will return "undefined", then when I click the object with id = 2 then it returns the object with id = 1 and so on. Even though the console.log on this.observable$ shows that its payload (value) is correct. I am not sure what is going on. I can't simply retrieve current value from this observable. If anything more about it is needed I'll submit additional info.

like image 673
ThatKidMike Avatar asked Sep 17 '26 01:09

ThatKidMike


1 Answers

You should avoid breaking the Observable chain wherever possible, and also avoid using local variables. Don't use your tmp variable and keep the observable$ instead, and instantiate it in ngOnInit(). Then, wherever you need to consume observable$, subscribe to it appropriately (generally using the async pipe):

ngOnInit() {
  this.observable$ = this.store.select(selectors.getObject);
}

showDialog(idClicked: string) {
  this.store.dispatch(new action.loadExampleAction(this.id));
}

Later, in a template somewhere:

<ng-container *ngIf="observable$ | async as myStuff">
</ng-container>
like image 139
Will Alexander Avatar answered Sep 18 '26 21:09

Will Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!