在Angular应用里使用Redux
生活随笔
收集整理的這篇文章主要介紹了
在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' }); // 1store.dispatch({ type: 'INCREMENT' }); // 2store.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的值:
然后執行監聽函數:
要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":
總結
以上是生活随笔為你收集整理的在Angular应用里使用Redux的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 指数型股票
- 下一篇: 加入公网github上的SAP orga