日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

在Angular应用里使用Redux

發布時間:2023/12/19 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 在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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。