NGRX原理

原理

  • component产生action
  • action触发effect,业务处理数据
  • store中存储state、reducer
  • reducer产生新的state
  • state修改,更新component

安装

1
npm install @ngrx/store

Counter示例

定义action

1
2
3
4
5
6
// .app/counter.action.ts
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');

定义reducer

1
2
3
4
5
6
7
8
9
10
11
import {createReducer, on} from '@ngrx/store';
import {increment, decrement, reset} from './counter.action.ts';

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: any, action: any){
return _counterReducer(state, action);
}

注册state

1
2
3
4
5
// app.module.ts
imports: [
BrowserModule,
StoreModule.forRoot({count: counterReducer})
]

定义Counter组件

1
2
3
4
5
6
7
<!--counter.component.html-->
<div>
{{counterNumber$ | async}}
<button (click)="increment()">incre</button>
<button (click)="decrement()">decre</button>
<button (click)="reset()">reset</button>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// counter.component.ts
import { Component } from '@angular/core';
import { select, Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { increment, decrement, reset } from 'src/app/counter.actions';

@Component({
selector: 'app-counter',
templateUrl: './counter.component.html',
styleUrls: ['./counter.component.css']
})
export class CounterComponent {
counterNumber$: Observable<number>;
constructor(private store: Store<{count: number}>){
this.counterNumber$ = store.pipe(select('count'));
}
increment(){
this.store.dispatch(increment());
}
decrement(){
this.store.dispatch(decrement());
}
reset(){
this.store.dispatch(reset());
}
}