How to get Value instead of Observable from NGRX Store in TS code

1.3k views Asked by At

Consider the following code

user$ = this._store.pipe(select(UserSelectors.selectUser));

Now we have an Observable that can be used like this:

  1. In View :
(user$ | async)?.name
  1. In Component (TS) :
   let storeValue: IUser;
   this.user$.pipe(take(1)).subscribe(value => storeValue = value);

So in my Component I implemented a getter:

    protected get user(): IUser {
        let storeValue: IUser;
        this.user$.pipe(take(1)).subscribe(value => storeValue = value);
        return storeValue;
    }

I am wondering if there is a way to use the selector to return the actual value, something like:

user = this._store.VALUE(select(UserSelectors.selectUser));

So all my getter logic is taken care of.

2

There are 2 answers

2
timdeschryver On

This isn't possible. I would even say that this is an anti-pattern.

0
daddykom On

NgRx ist a Redux implementation, which is designed for reactive programming.

Reactive:

  • Event happens
  • Triggers Action, which changes the store
  • can trigger effects, which read/write data and create actions (to change the store)
  • Views will consume the store with observables. Oberservable update the view every time the store changes. So every change of the store will be forward to the view.

Your way ist not reactive, thats why it does not work with NgRx. You can do it without a store or you must find a reactive way to solve your problem.