在ngrx中获取当前状态 [英] Get current state in ngrx

查看:93
本文介绍了在ngrx中获取当前状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一个最小示例在ngrx中打印当前状态:

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'});
  }
}

但是,这会在控制台中打印undefined:

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

我仍然无法创建一个最小样本来设法获取ngrx中的当前状态.

I still can't create a minimal sample that manages to get the current state in ngrx.

我已经看过在ngrx中获取当前状态,但是那里的答案对我不起作用,因为缺少store.take()store.value >.我的ngrx版本是"@ngrx/store": "^5.0.0",,那里的问题处理的是ngrx v1和v2.

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.

推荐答案

尝试为商店编写选择器:

Try to write a selector for your store:

export const getState = createFeatureSelector<YourStateInterface>('nameOfYourStore');

在组件中使用此选择器,将为您提供一个Observable,您可以随后对其进行订阅.

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);
 }
}

在模板中,您可以像这样使用Observable:

Within your template you can use the Observable like this:

<div>{{ myState|async|json }}</div>

..或者您像以前一样简单地在组件中订阅它,但是要小心并取消订阅ngOnDestroy方法内的订阅,以防止内存泄漏.

..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.

有关选择器的更多信息: https://toddmotto.com/ngrx-store-了解状态选择器

More information about selectors: https://toddmotto.com/ngrx-store-understanding-state-selectors

这篇关于在ngrx中获取当前状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆