首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >获取ngrx中的当前状态

获取ngrx中的当前状态
EN

Stack Overflow用户
提问于 2018-02-13 08:07:16
回答 2查看 4.5K关注 0票数 3

我试图用最小的例子在ngrx中打印当前状态:

代码语言:javascript
代码运行次数:0
运行
复制
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

代码语言:javascript
代码运行次数:0
运行
复制
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中获得当前状态的最小示例。

编辑:,我已经看过How to get current value of State object with @ngrx/store?Getting current state in ngrx了,但是答案对我没有用,因为store.take()store.value 缺少。我的ngrx版本是"@ngrx/store": "^5.0.0",,而这里的问题处理ngrx v1和v2。

EN

回答 2

Stack Overflow用户

发布于 2018-06-19 10:41:08

尝试为您的商店编写一个选择器:

代码语言:javascript
代码运行次数:0
运行
复制
export const getState = createFeatureSelector<YourStateInterface>('nameOfYourStore');

在您的组件中使用此选择器,将给您一个可观察的,然后您可以订阅。

代码语言:javascript
代码运行次数:0
运行
复制
@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);
 }
}

在模板中,您可以使用以下可观察到的内容:

代码语言:javascript
代码运行次数:0
运行
复制
<div>{{ myState|async|json }}</div>

..or --您只需像以前一样在组件中订阅它,但是要小心,不要订阅ngOnDestroy方法中的订阅,以防止内存泄漏。

有关选择器的更多信息:https://toddmotto.com/ngrx-store-understanding-state-selectors

票数 3
EN

Stack Overflow用户

发布于 2018-03-04 09:58:11

确保导入StoreModule,如app.module.ts中所示:

imports: [ BrowserModule, FormsModule, StoreModule.forRoot({ counter: Reducer }) ],

我试图在stackblitz:https://stackblitz.com/edit/angular-bjun7b上重新创建您的示例

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48762125

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档