angular + redux

Redux是什么?
Redux是全局的,唯一的,不可改变的内存状态数据库。
它有三个角色: Store, Action, Reducer


angular + redux_第1张图片
QQ截图20171227232349.png

Action可以理解为一个信号,它有一个type属性,这个是必须的,payload属性则是用来传递数据。
Store则是一个对象,存储所有的状态。Action通过Store的dispatch方法把数据传递给Reducer,Reducer接收到数据后返回一个新的状态(不改变原有的状态),然后把状态保存在Store。

接下来讲下如何在angular中使用Redux

首先,安装所需的插件。
1、在chrome浏览器中安装Redux DevTools插件,这个插件可以很直观的查看Redux的状态。
2、在angular项目中安装所需的模块

cnpm i --save @ngrx/[email protected] @ngrx/[email protected] @ngrx/[email protected] @ngrx/[email protected] @ngrx/[email protected] ngrx-store-freeze

接着,创建reducers和actions目录,用来存放reducer和action。
然后我们用一个例子来讲解下怎么使用Redux,这个例子是向服务器发送一个请求。那么就有三个状态,一个是发送请求的状态,一个是请求成功的状态,还有一个是请求失败的状态。
这样,我们就可以创建一个action文件用来存放这几个状态。
quote.action.ts

export const QUOTE = "Quote";
export const QUOTE_SUCCESS = "Quote Success";
export const QUOTE_FAIL = "Quote Fail";

接下来创建一个Reducer文件,用来处理相应的action,可以用“ngrx-reducer”命令快捷创建一个模板
quote.reducer.ts

import { LoadFailAction } from './../actions/quote.action';
import { Quote } from './../domain/quote.model';
import * as actions from '../actions/quote.action';

export interface State {
  quote: Quote
};

export const initialState: State = {    //初始状态
  quote: {
    "id": "1",
    "cn": "被击垮通常只是暂时的,但如果你放弃的话,就会使它成为永恒。(Marilyn vos Savant)",
    "en": "Being defeated is often a temporary condition. Giving up is what makes it permanent.",
    "pic": "/assets/img/quotes/1.jpg"
  }
};

export function reducer(state = initialState, action: actions.QuoteActions ): State {
  switch (action.type) {
    case actions.QUOTE_SUCCESS: {
      return {...state, quote: action.payload};  //返回一个新的state
    }

    case actions.QUOTE_FAIL:
    default: {
      return state;    //返回原有的state
    }
  }
}

export const getQuote = (state: State) => state.quote;

接着在reducers文件夹中创建一个index.ts,用来存放store
index.ts

import { state } from '@angular/animations';
import { NgModule } from '@angular/core';
import { environment } from './../../environments/environment.prod';
import { StoreModule, combineReducers, ActionReducer } from '@ngrx/store';
import { RouterStoreModule } from '@ngrx/router-store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { storeFreeze } from 'ngrx-store-freeze';  //用来冻结store,如果写入原有状态,就会报错
import { compose } from '@ngrx/core/compose';
import { createSelector } from 'reselect';

import * as fromQuote from './quote.reducer';
import * as fromAuth from './auth.reducer';

export interface State {
  quote: fromQuote.State
};

const reducers = {
  quote: fromQuote.reducer
}

const initialState: State = {
  quote: fromQuote.initialState
};

const productionReducers: ActionReducer = combineReducers(reducers);  //合并reducer
const developReducers: ActionReducer = compose(storeFreeze, combineReducers)(reducers);

export function reducer(state = initialState, action: any ): State {
  return environment.production ? productionReducers(state, action) : developReducers(state, action);  //根据环境返回不同的reducer
}


@NgModule({
  imports: [
    StoreModule.provideStore(reducer),
    RouterStoreModule.connectRouter(),
    StoreDevtoolsModule.instrumentOnlyWithExtension(),
  ]
})
export class AppStoreModule {}

然后在app.module.ts引入这个模块,接着就可以在login组件中使用

import { state } from '@angular/animations';
import { Quote } from './../../domain/quote.model';
import { Observable } from 'rxjs/Observable';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormGroup, FormControl } from '@angular/forms';
import {Store} from '@ngrx/store';
import * as fromRoot from './../../reducers';
import * as actions from './../../actions/quote.action';
import * as authActions from './../../actions/auth.action';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  form: FormGroup;
  quote$: Observable;

  constructor(private fb: FormBuilder,
    private quoteService$: QuoteService,
    private store$: Store) { }

  ngOnInit() {
    this.form = this.fb.group({
      email: ['[email protected]', Validators.compose([Validators.required, Validators.email])],
      password: ['', Validators.required]
    })
    this.quote$ = this.store$.select(state => state.quote.quote);  //reducer处理完后返回一个新的state,通过select方法获取到最新的state
    this.quoteService$
      .getQuote()
      .subscribe(q => {
        this.store$.dispatch({type:actions.QUOTE_SUCCESS, payload: q});   //把从服务器接收到的数据通过dispatch方法传递给reducer
      })
  }
}

你可能感兴趣的:(angular + redux)