NgRX-01

1. 介绍ngrx

ngrx 相当于 Angular 版本的 redux,是 Angular 的状态管理工具

2. 安装依赖

ng add方式,会自动生成所需文件并在app.module.ts中导入

ng add @ngrx/store
ng add @ngrx/store-devtools
ng add @ngrx/effects
ng add @ngrx/router-store

action.ts:为要改变数据的操作定义不同action
effects.ts(有数据请求的):通过判断action.type,来发起service
reducer.ts:判断action.type,返回新的store数据
component.ts:从store取数据

3. 计数器 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. 定义一个初始状态
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;

  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());
  }
}

{{count$ | async}}

你可能感兴趣的:(NgRX-01)