1. 介紹ngrx
ngrx 相當(dāng)于 Angular 版本的 redux缎浇,是 Angular 的狀態(tài)管理工具
2. 安裝依賴
ng add方式,會自動生成所需文件并在app.module.ts中導(dǎo)入
ng add @ngrx/store
ng add @ngrx/store-devtools
ng add @ngrx/effects
ng add @ngrx/router-store
action.ts:為要改變數(shù)據(jù)的操作定義不同action
effects.ts(有數(shù)據(jù)請求的):通過判斷action.type赴肚,來發(fā)起service
reducer.ts:判斷action.type素跺,返回新的store數(shù)據(jù)
component.ts:從store取數(shù)據(jù)
3. 計數(shù)器 demo
3.1 actions 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');
3.2 reducers counter.recuder.ts
import { createReducer, on, State } from '@ngrx/store';
import * as Actions from './counter.action';
// 1. 定義一個初始狀態(tài)
const initialState = 0;
const _reducer = createReducer(
initialState,
on(Actions.increment, state => state + 1),
on(Actions.decrement, state => state - 1),
on(Actions.reset, _ => 0)
);
export const counterReducer = (state, action) => {
return _reducer(state, action);
};
3.3 模塊注冊 app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { counterReducer } from './counter.reducer';
import { StoreModule } from '@ngrx/store';
import { MyCounterComponent } from './my-counter/my-counter.component';
@NgModule({
imports: [BrowserModule, StoreModule.forRoot({ counter: counterReducer })], //引入 storeModule
declarations: [AppComponent, MyCounterComponent],
bootstrap: [AppComponent]
})
export class AppModule {}
3.4 編寫組件
// my-counter.component.ts
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';
import * as counterActions from '../counter.action';
@Component({
selector: 'app-my-counter',
templateUrl: './my-counter.component.html',
styleUrls: ['./my-counter.component.css']
})
export class MyCounterComponent {
count$: Observable<number>;
constructor(private store$: Store<{ counter: number }>) {
// create count$
this.count$ = store$.select('counter');
console.log(this.count$);
}
increment() {
this.store$.dispatch(counterActions.increment());
}
decrement() {
this.store$.dispatch(counterActions.decrement());
}
reset() {
this.store$.dispatch(counterActions.reset());
}
}
<p>
{{count$ | async}}
</p>
<button (click)="increment()">increment</button>
<button (click)="decrement()">decrement</button>
<button (click)="reset()">reset</button>