使用ngrx一次获取商店的当前状态 [英] Using ngrx to obtain store's current state once

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

问题描述

我想知道是否有人知道如何一次获取商店的当前状态而不必订阅它.我目前正在使用ngrx订阅商店并访问其状态以设置组件的属性,但是由于我已订阅,因此该属性会不断刷新.因此,我正在寻找一种仅获取一次此属性的方法,以便可以显示数据而无需不断刷新.

Hi I was wondering if anyone know how to get a store's current state once without having to subscribe to it. I'm currently using ngrx to subscribe to the store and access its state to set a component's attribute, but since I'm subscribed this attribute is constantly refreshing. So I'm looking for a way to obtain this attribute just once so that I can display data without it refreshing constantly.

以防万一,这发生在组件的构造函数中.

Just in case, this happens inside my component's constructor.

我一直在尝试这样的事情:

I've been trying something like this:

_store.select('storeData.correlationData');

订阅时,我将这样访问:

When subscribing I would access like this:

_store.subscribe(
  (state) => {
    this.correlationData = state.storeData.correlationData;
  }
);

编辑

应用状态:

export interface ApplicationState {
  uiState: UiState;
  storeData: StoreData;
}

推荐答案

您可以创建getState()函数,将其放在共享模块中,然后在需要的地方导入.关键是使用take(1)运算符使其同步:

You can create getState() function, put it in a shared module and import where needed. The key is to make it synchronous by using take(1) operator:

export function getState(store: any, selector: string) {
  let _state: any;
  store.take(1).subscribe(o => _state = o);
  return _state;
}

这是我正在使用的更高级的版本:

Here's more advanced version I'm using:

export function getState(store: any, selector?: any) {
  let _state: any;
  let state$: any;

  if (typeof selector === 'string' && /\./g.test(selector)) {
    state$ = store.pluck(...selector.split('.'));
  } else if (typeof selector === 'string') {
    state$ = store.map(state => state[selector]);
  } else if (typeof selector === 'function') {
    state$ = store.map(state => selector(state));
  } else {
    state$ = store;
  }
  state$.take(1)
    .subscribe(o => _state = o);
  return _state;
}

通过这种方式,您可以通过几种不同的方式获得状态:

With this you can get state in few different ways:

getState(this.store) // all data in Store
getState(this.store, 'users')
getState(this.store, state => state.users)
getState(this.store, 'users.address.street') // Cool!

请谨慎使用!

@Maximes在注释中指出,您应该尝试直接在代码中使用Observables,并使用此方法进行测试.

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

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