我正在关注示例应用程序(https://github.com/ngrx/example-app),我所有的商店、效果、动作都运行良好,但是在使用 reducer 文件中定义的选择器与定义的选择器时,我的行为很奇怪在容器文件中。reducer 文件中定义的选择器返回函数,而容器文件中定义的选择器返回对象。我复制了代码片段来详细解释这一点。我想定义共享选择器,因此它易于维护和升级,而不是每次都在容器组件中定义。如果有人阐明解决此问题,我将不胜感激。
//package.json
{
dependencies: {
"@angular/common": "2.2.1",
"@angular/compiler": "2.2.1",
"@angular/compiler-cli": "2.2.1",
"@angular/core": "2.2.1",
"@angular/forms": "2.2.1",
"rxjs": "^5.0.0-beta.12",
"@ngrx/core": "^1.2.0",
"@ngrx/effects": "^2.0.0",
"@ngrx/store": "^2.2.1",
"@ngrx/store-devtools": "^3.2.3",
"reselect": "^2.5.4"
....
},
}
//space.reducer.ts //空间接口和reducer
export interface SpaceState {
lastUpdated?: Date,
spacesLoaded: boolean,
spaces: {[key: string]: Space}
}
export const INITIAL_STATE: SpaceState = {
lastUpdated: new Date(),
spacesLoaded: false,
spaces: {},
};
export const getMap = (state: SpaceState) => state.spaces;
//application.reducer.ts //组合状态接口和reducer
import * as fromSpace from "./space.reducer.ts";
export interface ApplicationState{
spaceState: SpaceState
}
export const INITIAL_APPLICATION_STATE: ApplicationState = {
spaceState: fromSpace.INITIAL_STATE
};
const reducers = {
spaceState: fromSpace.reducer
};
const reducer: ActionReducer<ApplicationState> = combineReducers(reducers);
export function reducer(state: any, action: any) {
return reducers;
}
export const getSpaceState = (state: ApplicationState) => state.spaceState;
export const getSpaceMap = (state: ApplicationState) => createSelector(getSpaceState, fromSpace.getMap);
//spaces.container.ts //容器组件
export class SpacesComponent implement onInit() {
constructor(private store: Store<ApplicationState>) {}
ngOnInit(): void {
this.store.select(getSpaceMap).subscribe(map => {
console.log("subscribe of space-map (using shared func) from container: " + map);
});
this.store.select((state) => state.spaceState.spaces).subscribe(map => {
console.log("subscribe of space-map (using container func) from container: " + map);
});
}
}
//容器输出
subscribe of space-map (using shared func) from container: function selector(state, props) {
for (var _len4 = arguments.length, args = Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) {
args[_key4 - 2] = arguments[_key4];
}
var params = dependencies.map(function (dependency) {
return dependency.apply(undefined, [state, props].concat(args));
});
return memoizedResultFunc.apply(undefined, _toConsumableArray(params));
}
subscribe of space-map (using container func) from container: [object Object]