【发布时间】:2018-07-06 10:21:15
【问题描述】:
出于某种原因,我的所有选择器都返回了整个状态对象,而不是我认为应该返回的子状态。例如,我试图从 reducers/customer.ts 返回客户状态,但我从 index.ts 中获取了一个包含整个状态的对象。
在检查了 github 上的 ngrx 示例应用程序后,我选择了下面的特定结构,显然我做错了什么。
这是actions/customer.ts:
import { Action } from '@ngrx/store';
import { State } from '../reducers/customer';
export enum CustomerActionTypes {
Add = '[Customer] Add Selected Customer to Store'
}
export class Add implements Action {
readonly type = CustomerActionTypes.Add;
constructor(public payload: State) {
console.log("from action: " + JSON.stringify(payload,null,2));
}
}
export type CustomerActions = Add
还有reducers/customer.ts:
import { ActionReducer, Action } from '@ngrx/store';
import { CustomerActionTypes, CustomerActions } from '../actions/customer';
export interface State {
name: string;
status: string;
phone: string;
stage: string;
type: string;
id: string;
street: string;
city: string;
postalCode: string;
email: string;
state: string;
}
export function reducer(
state: State,
action: CustomerActions
): State {
switch (action.type) {
case CustomerActionTypes.Add:
return action.payload
default:
return state;
}
}
export const getCustomerState = (state: State) => state;
还有reducers/index.ts:
//For reducers map
import * as fromMainNav from './main-nav-ui';
import * as fromTradeUI from './trade-ui';
import * as fromAppts from './appointments';
import * as fromCustomer from './customer';
//Whole application state
export interface State {
mainNavUI: fromMainNav.State;
tradeUI: fromTradeUI.State;
appointments: fromAppts.State;
selectedCustomer: fromCustomer.State;
}
//Reducer map
export const reducers = {
mainNavUI: fromMainNav.reducer,
tradeUI: fromTradeUI.reducer,
appointments: fromAppts.reducer,
selectedCustomer: fromCustomer.reducer
};
并在 app.module.ts 中导入:
imports: [
...
StoreModule.forRoot(reducers)
],
最后我是如何将它连接到一个组件中并使用选择器的:
...
import * as fromCustomer from '../../../shared/state/reducers/customer';
...
public cust$: Observable<fromCustomer.State>;
constructor(
...
public ngrxStore: Store<fromCustomer.State>
) {
this.cust$ = ngrxStore.select(fromCustomer.getCustomerState);
}
任何帮助将不胜感激,谢谢!
【问题讨论】:
标签: angular selector state store ngrx