获取ngrx中的当前状态

时间:2018-02-13 08:07:16

标签: ngrx

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

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

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,但那里的答案对我不起作用,因为{{1} }和store.take() 缺失。我的ngrx版本是store.value,而那里的问题处理ngrx v1和v2。

2 个答案:

答案 0 :(得分:1)

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

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

在组件中使用此选择器,将为您提供一个Observable,然后您可以订阅它。

@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:

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

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

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

答案 1 :(得分:0)

确保按照app.module.ts中的方式导入StoreModule:
imports: [ BrowserModule, FormsModule, StoreModule.forRoot({ counter: Reducer }) ],

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

相关问题