在Angular中使用NGXS状态管理
warning:
这篇文章距离上次修改已过191天,其中的内容可能已经有所变动。
import { State, Action, StateContext } from '@ngxs/store';
// 定义一个简单的用户模型
export interface User {
name: string;
age: number;
}
// 定义初始状态
@State<User>({
name: 'user',
defaults: {
name: 'Guest',
age: 0
}
})
export class UserState {
// 定义一个动作来更新用户信息
@Action(UpdateUserAction)
updateUser(ctx: StateContext<User>, action: UpdateUserAction) {
const state = ctx.getState();
ctx.patchState({
...state,
...action.payload
});
}
}
// 创建一个动作类用于更新用户信息
export class UpdateUserAction {
static readonly type = 'UpdateUserAction';
constructor(public payload: User) {}
}
// 在组件中触发动作来更新用户状态
import { Store } from '@ngxs/store';
export class SomeComponent {
constructor(private store: Store) {}
updateUserInfo(user: User) {
this.store.dispatch(new UpdateUserAction(user));
}
}
这个例子展示了如何在Angular应用中使用NGXS状态管理库来管理用户状态。首先定义了一个用户模型和一个初始状态,然后创建了一个动作来更新用户信息。在组件中,我们可以通过调用store.dispatch
方法来触发这个动作,从而更新用户状态。
评论已关闭