Skip to content

NgRx 是一个基于 Redux 模式和 RxJS 的状态管理库,用于在 Angular 应用中进行可预测性的状态管理。下面将介绍 NgRx 的基本使用步骤。

1. 安装 NgRx

首先,你需要安装 NgRx 相关的包。通常,你需要安装 @ngrx/store(核心状态管理库)和 @ngrx/effects(用于处理副作用)。

bash
npm install @ngrx/store @ngrx/effects --save

2. 创建状态(State)

在你的应用中,定义你需要管理的状态。这个状态可以是一个 JavaScript 对象,其中包含应用程序的各种数据。

ts
// app.state.ts

export interface AppState {
  user: User;
  // ...其他状态属性
}

export interface User {
  id: number;
  name: string;
}

3. 创建 Action

**Actions 是描述状态更改的纯对象。**你需要定义各种可能的动作,以及它们对应的 payload 数据。

ts
// user.actions.ts

import { createAction, props } from '@ngrx/store';

export const setUser = createAction(
  '[User] Set User',
  props<{ user: User }>()
);

4. 创建 Reducer

Reducers 是纯函数,用于根据接收到的 Action 更新状态。每个 Action 都会触发一个 Reducer,并根据 Action 类型对状态进行更新。

ts
// user.reducer.ts

import { createReducer, on } from '@ngrx/store';
import { setUser } from './user.actions';

const initialState: User = {
  id: null,
  name: null
};

const userReducer = createReducer(
  initialState,
  on(setUser, (state, { user }) => ({ ...state, ...user }))
);

export function reducer(state, action) {
  return userReducer(state, action);
}

5. 注册 Store

将你的 Reducer 注册到 Angular 应用的全局状态管理 Store 中。

ts
// app.module.ts

import { StoreModule } from '@ngrx/store';
import { reducer } from './user.reducer';

@NgModule({
  declarations: [
    // ... components
  ],
  imports: [
    // ... other modules
    StoreModule.forRoot({ user: reducer })  // Register your reducer
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

6. 使用 Store

现在你可以在你的组件中使用 Store 来分发 Actions,并订阅状态的变化。

ts
// your-component.component.ts

import { Store, select } from '@ngrx/store';
import { setUser } from './user.actions';
import { AppState, User } from './app.state';

@Component({
  // ... component configuration
})
export class YourComponent implements OnInit {
  user: User;

  constructor(private store: Store<AppState>) { }

  ngOnInit() {
    this.store.pipe(select('user')).subscribe(user => {
      this.user = user;
    });
  }

  updateUser() {
    const user: User = { id: 1, name: 'John Doe' };
    this.store.dispatch(setUser({ user }));
  }
}

在上述代码中,我们使用 Store 来分发一个 Action,并在组件中订阅状态变化。在组件初始化时,我们订阅了用户状态,当用户状态发生变化时,我们会收到通知并更新组件中的 user 对象。

这是一个简单的 NgRx 的基本使用示例。根据你的应用需求,你可以定义更多的 Action、Reducer 和 Effect,并结合 RxJS 进行更复杂的状态管理。