在Angular中创建项目时,我一直非常密切关注https://github.com/ngrx/example-app。
我试图从我的组件中的根reducer中选择一个值,但它无法正常工作。
有问题的组件(和行):
import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Store } from '@ngrx/store';
import * as rootReducer from '../../reducer/';
import * as layoutActions from '../../actions/layout';
@Component({
selector: 'app-nav-bar',
template: `
<nav>
<div class="logo">
linkme
</div>
<a routerLink="/home">Home</a>
<a routerLink="/groups">Groups</a>
<div class="button" (click)="toggleAddModal()">add thing</div>
</nav>
<add-link-modal [open]="showAddModal$ | async"></add-link-modal>
`,
styleUrls: ['./nav-bar.component.scss']
})
export class NavBarComponent {
showAddModal$: Observable<boolean>;
constructor(private store : Store<rootReducer.State>) {
****** this.showAddModal$ = store.select(rootReducer.getShowAddModal); ****** this is the line that is breaking
}
toggleAddModal()
{
this.store.dispatch({type: layoutActions.TOGGLE_ADD_MODAL})
}
}
&#13;
app.module.ts
...
import { Store, StoreModule } from '@ngrx/store';
import { reducers } from './reducer/'
import { AppComponent } from './app.component';
...
@NgModule({
...
imports: [
...
StoreModule.provideStore(reducers)
...
],
..
})
export class AppModule { }
&#13;
减速器/ index.ts
import { combineReducers } from '@ngrx/store';
import { createSelector } from 'reselect';
import { ActionReducer } from '@ngrx/store';
import * as fromLinks from './links';
import * as fromLayout from './layout';
export interface State{
layout: fromLayout.LayoutState
links: fromLinks.LinkState
}
const globalReducers = {
layoutReducer:fromLayout.layoutReducer,
linksReducer: fromLinks.linkReducer
};
const globalState: ActionReducer<State> = combineReducers(globalReducers);
export function reducers(state: any, action: any) { return globalState(state, action);}
/*layout*/
export const getLayoutState = (state: State) => state.layout;
export const getShowAddModal = createSelector(getLayoutState, fromLayout.getShowAddModal);
&#13;
减速器/ layout.ts
import { ActionReducer, Action } from '@ngrx/store';
import * as layoutActions from '../actions/layout';
export interface LayoutState {
showAddModal: boolean;
}
const initialState: LayoutState = {
showAddModal: false,
};
export function layoutReducer(state = initialState, action: Action): LayoutState {
switch (action.type) {
case layoutActions.TOGGLE_ADD_MODAL:
const newBoolState = state.showAddModal ? false : true ;
return {
showAddModal: newBoolState
};
default:
return state;
}
}
export const getShowAddModal = (state: LayoutState) => state.showAddModal; *** This is the undefined value
&#13;
我在layout.ts中的方法Cannot read property 'showAddModal' of undefined
中收到了一个TypeError:getShowAddModal
。知道我做错了什么吗?它几乎与示例中的一样精确。这是reducer文件夹,其中包含我一直密切关注的文件:https://github.com/ngrx/example-app/tree/master/src/app/reducers
任何帮助将不胜感激。