Nicolae Daian
Nicolae Daian

Reputation: 1155

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

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.

Upvotes: 0

Views: 1553

Answers (2)

daddykom
daddykom

Reputation: 220

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.

Upvotes: 1

timdeschryver
timdeschryver

Reputation: 15505

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

Upvotes: 1

Related Questions