参考文档:
1,简单使用
2021年7月6日10:31:12 :发现还有一个componentStore的概念。
1,几个概念
- Actions,描述了组件或者服务发出的唯一事件
- reducers,这是一个纯函数,通过计算当前的状态和最近的action得到最新的状态。
- Selectors, 这个纯函数用来选择,派生和组合状态。
- state,状态是通过store访问的,它是状态的可观察对象和工作的观察者。
2,具体步骤
1,定义action
import { createAction } from '@ngrx/store';
export const increment = createAction('[Counter Component] Increment');
export const decrement = createAction('[Counter Component] Decrement');
export const reset = createAction('[Counter Component] Reset');
2, 定义reducer
import { createReducer, on } from '@ngrx/store';
import { increment, decrement, reset } from './counter.actions';
export const initialState = 0;
const _counterReducer = createReducer(
initialState,
on(increment, (state) => state + 1),
on(decrement, (state) => state - 1),
on(reset, (state) => 0)
);
export function counterReducer(state, action) {
return _counterReducer(state, action);
}
3, app.module.ts文件
import { AppComponent } from './app.component';
import { StoreModule } from '@ngrx/store';
import { counterReducer } from './counter.reducer';
import { MyCounterComponent } from './my-counter/my-counter.component';
@NgModule({
declarations: [
AppComponent,
MyCounterComponent
],
imports: [
BrowserModule,
StoreModule.forRoot({ count: counterReducer })
],
providers: [],
bootstrap: [
AppComponent
],
})
export class AppModule { }
4, 定义子组件 my-counter.component.ts
my-counter.component.ts
import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { increment, decrement, reset } from '../counter.actions';
@Component({
selector: 'app-my-counter',
templateUrl: './my-counter.component.html',
})
export class MyCounterComponent {
count$: Observable<number>;
constructor(private store: Store<{ count: number }>) {
this.count$ = store.select('count');
}
increment() {
this.store.dispatch(increment());
}
decrement() {
this.store.dispatch(decrement());
}
reset() {
this.store.dispatch(reset());
}
}
my-counter.component.HTML
<button id="increment" (click)="increment()">Increment</button>
<div>Current Count: {{ count$ | async }}</div>
<button id="decrement" (click)="decrement()">Decrement</button>
<button id="reset" (click)="reset()">Reset Counter</button>
5,在app.component组件中引用
<h1>NgRx Tutorial</h1>
<app-my-counter></app-my-counter>