在Angular应用里使用Redux

时间:2022-07-25
本文章向大家介绍在Angular应用里使用Redux,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

ngrx是Angular基于Rxjs的状态管理,保存了Redux的核心概念,并使用RxJs扩展的Redux实现。使用Observable来简化监听事件和订阅等操作。Redux 是 JavaScript 状态容器,提供可预测化的状态管理。 应用中所有的 state 都以一个对象树的形式储存在一个单一的 store 中。 惟一改变 state 的办法是触发 action,一个描述发生什么的对象。

看个例子:

import { of, fromEvent, interval, Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import { map, switchMap } from 'rxjs/operators';
import { tap } from 'rxjs/operators';
import { OperatorFunction } from 'rxjs';
import { createStore } from 'redux';

@Injectable()
export class JerrySandBoxService{
    name = 'Jerry';
    jerryMap: OperatorFunction<Event, number> = switchMap(this.jerryintervalFunction);

    jerryintervalFunction(event: Event){
        console.log('event: ' + event.timeStamp );
        /*
        returns an Observable that emits an infinite sequence of ascending integers, with a constant interval of time of your choosing between those emissions.*/

        //const a = interval(1000);
        //return a;
        // return event.timeStamp;
        return of(event.timeStamp);
    }

    counter(state: 0, action){
        switch (action.type) {
            case 'INCREMENT':
              return state + 1;
            case 'DECREMENT':
              return state - 1;
            case '@@redux/INIT':
              return 0;
            default:
              return state;
            }
    }

    
    print2(){
        const store = createStore(this.counter);
        store.subscribe(() =>
            console.log(store.getState())
        );

        // 改变内部 state 惟一方法是 dispatch 一个 action。
// action 可以被序列化,用日记记录和储存下来,后期还可以以回放的方式执行
        store.dispatch({ type: 'INCREMENT' });
// 1
        store.dispatch({ type: 'INCREMENT' });
// 2
        store.dispatch({ type: 'DECREMENT' });
// 1
    }

    print(){
        /*
        const observable = of(1, 2, 3);
        const newObservable = observable.pipe(
            tap(num => console.log(num)),
            map(num => 'hello world: ' + num)
        );
        newObservable.subscribe(data => console.log('in subscribe: ' + data));*/
        const clicks: Observable<Event> = fromEvent(document, 'click');

        const result = clicks.pipe(this.jerryMap);
        //result.subscribe(x => console.log(x));
        result.subscribe(x => {
            console.log(x);
        });
    }
}

添加redux依赖,然后npm install:

测试输出:

counter是一个JavaScript function,接收state和action两个输入参数,术语叫reducer:

store创建后,首先初始化:

这里就会直接调用应用程序写的reducer:

这里注册监听事件:

实际上就是添加到一个监听数组里:

再次执行dispatch,改变state的值:

然后执行监听函数: