如果您想将效果与商店分开,您可以定义一个基本状态类:
@State<Customer>( {
name: 'customer'
})
export class CustomerState {
constructor() { }
@Action(ChangeCustomerSuccess)
changeCustomerSuccess({ getState, setState }: StateContext<Customer>, { payload }: ChangeCustomerSuccess ) {
const state = getState();
// Set the new state. No service logic here.
setState( {
...state,
firstname: payload.firstname, lastname: lastname.nachname
});
}
}
然后您将从该状态派生并将您的服务逻辑放入派生类中:
@State<Customer>({
name: 'customer'
})
export class CustomerServiceState extends CustomerState {
constructor(private customerService: CustomerService, private store: Store) {
super();
}
@Action(ChangeCustomerAction)
changeCustomerService({ getState, setState }: StateContext<Customer>, { payload }: ChangeCustomerAction) {
// This action does not need to change the state, but it can, e.g. to set the loading flag.
// It executes the (backend) effect and sends success / error to the store.
this.store.dispatch( new ChangeCustomerSuccess( payload ));
}
}
在我浏览的任何 NGXS 示例中,我都没有看到这种方法,但我一直在寻找一种方法来分离这两个问题——UI 和后端。