fiddlest
fiddlest

Reputation: 1302

Angular 8 ngrx store how to get reducer value without subscribe callback?

I am new to the angular and rx.

I see a lot of examples just use code something like this.

this.store.select('city')
this.store.pipe(select(action()))

However, those code just returning _Store instance.

The correct way to get value from reducer is that

this.store.pipe(select(action())).subscribe(val => this.val)

Is there any way I can just get value from reducer without callback or subscribe?

Something like generator in redux saga ??

const city = yield select(state => state.city) 

Upvotes: 2

Views: 6555

Answers (2)

Krzysztof Platis
Krzysztof Platis

Reputation: 1221

If you just need a value in a html template, I suggest not subscribing, but referencing this observable directly in the template together with an async pipe.

//typescript
public value$ = this.store.pipe(select(...));
//html
{{ value$ | async }}

If you need a value of the stream in the TS code and you want to unsubscribe from the observable just after accessing the value (you dont want to call callback whenever new value is emmited), you can use operator take(1):

this.store.pipe(select(...)).pipe(take(1)).subscribe(...)

Upvotes: 4

Eric Simonton
Eric Simonton

Reputation: 6039

I use a wrapper (that I wrote) around ngrx/store, and it allows such an operation using code like this:

store('city').state(); // returns the current value of `city`

Or, equivalently (and more recommended according to its style guide):

store.state().city;

The wrapper is ng-app-state. It is a shift in thinking from the traditional action/reducer patterns of ngrx, but one that has worked well for me.

Upvotes: 0

Related Questions