问题
I'm trying to print the current state in ngrx using a minimal example:
interface AppState {
counter : number;
}
export function Reducer(state : AppState = { counter : 0 }, action : Action) {
console.log(`counter: ${state.counter}`);
return { counter: state.counter + 1 };
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
constructor(private store : Store<AppState>) {
let observable : Observable<number>;
store.dispatch({type:'foo'});
store.dispatch({type:'foo'});
store.select('counter').subscribe(x => console.log(x));
store.dispatch({type:'foo'});
store.dispatch({type:'foo'});
}
}
This, however, prints undefined
in the console:
counter: 0
app.component.ts:10 counter: 1
app.component.ts:10 counter: 2
app.component.ts:29 undefined <---- It prints undefined
app.component.ts:10 counter: 3
app.component.ts:10 counter: 4
I still can't create a minimal sample that manages to get the current state in ngrx.
Edit: I've already looked at How to get current value of State object with @ngrx/store? and Getting current state in ngrx, but the answers there don't work for me, because store.take()
and store.value
are missing. My ngrx version is "@ngrx/store": "^5.0.0",
, while the questions there handle ngrx v1 and v2.
回答1:
Try to write a selector for your store:
export const getState = createFeatureSelector<YourStateInterface>('nameOfYourStore');
Using this selector within your component, will give you a Observable which you can then subscribe on.
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
myState: Observable<AppState>
constructor(private store : Store<AppState>) {
this.myState = this.store.select(fromRoot.getState);
}
}
Within your template you can use the Observable like this:
<div>{{ myState|async|json }}</div>
..or you simply subscribe it within your component just like you did it before, but be careful and unsubscribe from the subscription inside the ngOnDestroy method in order to prevent a memory leak.
More information about selectors: https://toddmotto.com/ngrx-store-understanding-state-selectors
回答2:
Make sure you import the StoreModule as followed in you app.module.ts:
imports: [
BrowserModule,
FormsModule,
StoreModule.forRoot({ counter: Reducer })
],
I tried to recreate your example on stackblitz: https://stackblitz.com/edit/angular-bjun7b
来源:https://stackoverflow.com/questions/48762125/get-current-state-in-ngrx