我试图用最小的例子在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了,但是答案对我没有用,因为store.take()
和store.value
缺少。我的ngrx版本是"@ngrx/store": "^5.0.0",
,而这里的问题处理ngrx v1和v2。
发布于 2018-06-19 02:41:08
尝试为您的商店编写一个选择器:
export const getState = createFeatureSelector<YourStateInterface>('nameOfYourStore');
在您的组件中使用此选择器,将给您一个可观察的,然后您可以订阅。
@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);
}
}
在模板中,您可以使用以下可观察到的内容:
<div>{{ myState|async|json }}</div>
..or --您只需像以前一样在组件中订阅它,但是要小心,不要订阅ngOnDestroy方法中的订阅,以防止内存泄漏。
有关选择器的更多信息:https://toddmotto.com/ngrx-store-understanding-state-selectors
发布于 2018-03-04 01:58:11
确保导入StoreModule,如app.module.ts中所示:
imports: [ BrowserModule, FormsModule, StoreModule.forRoot({ counter: Reducer }) ],
我试图在stackblitz:https://stackblitz.com/edit/angular-bjun7b上重新创建您的示例
https://stackoverflow.com/questions/48762125
复制