Get current state in ngrx

别来无恙 提交于 2019-12-24 08:48:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!