How to get current value of State object with @ngrx/store? How to get current value of State object with @ngrx/store? angular angular

How to get current value of State object with @ngrx/store?


Original answer for @ngrx/store v1.x

@ngrx/store extends BehaviorSubject and it has a value property you can use.

this._store.value

that will be the current state of your app, and from there you can select properties, filter, map etc...

update:

Took me a while to figure what's what in your example (: To get current value of dataForUpdate, you can use:

let x = this._store.value.StateReducer.dataForUpdate;console.log(x); // => { key: "123" }

Update for @ngrx/store v2.x

With the update to version 2, value was removed as described in docs:

The APIs for synchronously pulling the most recent state value out of Store have been removed. Instead, you can always rely on subscribe() running synchronously if you have to get the state value:

function getState(store: Store<State>): State {    let state: State;    store.take(1).subscribe(s => state = s);    return state;}


Following the answer from @Sasxa, the syntax changed on newer versions of @nrgx/store (v5 and v6). After the underlying RxJS library was updated to ^5.5.0, there is now a pipe method available on all the Observable instances, which allows for easier chaining and changes how a subscription is achieved.

So you can now do something like:

import { take } from 'rxjs/operators';function getState(store: Store<State>): State {   let state: State;   store.select('your-state').pipe(take(1)).subscribe(      s => state = s   );   return state;}

Or, using strictly the pipe() operator:

import { select } from '@ngrx/store';import { take } from 'rxjs/operators';function getState(store: Store<State>): State {   let state: State;   store.pipe(select('your-state'), take(1)).subscribe(      s => state = s   );   return state;}

And if you want to make your code a bit more readable you can also employ async/await mechanics like so:

import { select } from '@ngrx/store';import { take } from 'rxjs/operators';function async getStateAsync(store: Store<State>): State {   let state = await store             .pipe(                select('your-state'),                take(1)             )             .toPromise<State>();   return state;}


Not strictly a direct answer to the question, but I found this page looking for how to retrieve a single value from the store.

To achieve this, you can inject the State object from @ngrx/store as shown below:

import { State } from '@ngrx/store';constructor (private state: State<AppState>) {    let propertyValue = state.getValue().path.to.state.property;}

The state object holds the current state in a private _value property, accessed by the .getValue() method.