這篇文章帶大家深入了解一下angular的狀態(tài)管理器NgRx,介紹一下NgRx的使用方法,希望對大家有幫助!
NgRx 是 Angular 應(yīng)用程式中實(shí)作全域狀態(tài)管理的 Redux 架構(gòu)解決方案。 【相關(guān)教學(xué)推薦:《angular教學(xué)》】
#@ngrx/store:全域狀態(tài)管理模組
@ngrx/effects:處理副作用
#@ngrx/store-devtools:瀏覽器偵錯(cuò)工具,需要依賴Redux Devtools Extension
#@ngrx/schematics:命令列工具,快速產(chǎn)生NgRx 檔案
@ngrx/entity:提高開發(fā)者在Reducer 中操作資料的效率
@ngrx/router-store:將路由狀態(tài)同步到全域Store
#快速開始
1、下載NgRx
npm install @ngrx/store @ngrx/effects @ngrx/entity @ngrx/router-store @ngrx/store-devtools @ngrx/schematics
2、設(shè)定NgRx CLI
ng config cli.defaultCollection @ngrx/schematics
// angular.json "cli": { "defaultCollection": "@ngrx/schematics" }
3、建立Store
ng g store State --root --module app.module.ts --statePath store --stateInterface AppState
##4 、建立Action
ng g action store/actions/counter --skipTests
import { createAction } from "@ngrx/store" export const increment = createAction("increment") export const decrement = createAction("decrement")
#5、建立Reducer
#ng g reducer store/reducers/counter --skipTests --reducers=../index.ts
import { createReducer, on } from "@ngrx/store" import { decrement, increment } from "../actions/counter.actions" export const counterFeatureKey = "counter" export interface State { count: number } export const initialState: State = { count: 0 } export const reducer = createReducer( initialState, on(increment, state => ({ count: state.count + 1 })), on(decrement, state => ({ count: state.count - 1 })) )
6、建立Selector
#ng g selector store/selectors/counter --skipTests
import { createFeatureSelector, createSelector } from "@ngrx/store" import { counterFeatureKey, State } from "../reducers/counter.reducer" import { AppState } from ".." export const selectCounter = createFeatureSelector<AppState, State>(counterFeatureKey) export const selectCount = createSelector(selectCounter, state => state.count)
7、元件類別觸發(fā)Action、取得狀態(tài)
import { select, Store } from "@ngrx/store" import { Observable } from "rxjs" import { AppState } from "./store" import { decrement, increment } from "./store/actions/counter.actions" import { selectCount } from "./store/selectors/counter.selectors" export class AppComponent { count: Observable<number> constructor(private store: Store<AppState>) { this.count = this.store.pipe(select(selectCount)) } increment() { this.store.dispatch(increment()) } decrement() { this.store.dispatch(decrement()) } }
8、元件模板顯示狀態(tài)
<button (click)="increment()">+</button> <span>{{ count | async }}</span> <button (click)="decrement()">-</button>
Action Payload
1、在元件中使用dispatch 觸發(fā)Action 時(shí)傳遞參數(shù),參數(shù)最終會被放置在Action 物件中。this.store.dispatch(increment({ count: 5 }))2、建立 Action Creator 函數(shù)時(shí),取得參數(shù)並指定參數(shù)類型。
import { createAction, props } from "@ngrx/store" export const increment = createAction("increment", props<{ count: number }>())
export declare function props<P extends object>(): Props<P>;3、在 Reducer 中透過 Action 物件取得參數(shù)。
export const reducer = createReducer( initialState, on(increment, (state, action) => ({ count: state.count + action.count })) )
MetaReducer
metaReducer 是 Action -> Reducer 之間的鉤子,允許開發(fā)者對 Action 進(jìn)行預(yù)處理 (在普通 Reducer 函數(shù)呼叫之前呼叫)。function debug(reducer: ActionReducer<any>): ActionReducer<any> { return function (state, action) { return reducer(state, action) } } export const metaReducers: MetaReducer<AppState>[] = !environment.production ? [debug] : []
Effect
需求:在頁面中新增一個(gè)按鈕,點(diǎn)擊按鈕後延遲一秒鐘讓數(shù)值增加。 1、在元件模板中新增一個(gè)用於非同步數(shù)值增加的按鈕,按鈕被點(diǎn)擊後執(zhí)行increment_async 方法
<button (click)="increment_async()">async</button>2、在元件類別中新增
increment_async 方法,並在方法中觸發(fā)執(zhí)行非同步操作的Action
increment_async() { this.store.dispatch(increment_async()) }3、在Action 檔案中新增執(zhí)行非同步操作的Action
export const increment_async = createAction("increment_async")4、創(chuàng)建Effect,接收Action 並執(zhí)行副作用,繼續(xù)觸發(fā)Action
ng g effect store/effects/counter --root --module app.module.ts --skipTests
import { Injectable } from "@angular/core" import { Actions, createEffect, ofType } from "@ngrx/effects" import { increment, increment_async } from "../actions/counter.actions" import { mergeMap, map } from "rxjs/operators" import { timer } from "rxjs" // createEffect // 用于創(chuàng)建 Effect, Effect 用于執(zhí)行副作用. // 調(diào)用方法時(shí)傳遞回調(diào)函數(shù), 回調(diào)函數(shù)中返回 Observable 對象, 對象中要發(fā)出副作用執(zhí)行完成后要觸發(fā)的 Action 對象 // 回調(diào)函數(shù)的返回值在 createEffect 方法內(nèi)部被繼續(xù)返回, 最終返回值被存儲在了 Effect 類的屬性中 // NgRx 在實(shí)例化 Effect 類后, 會訂閱 Effect 類屬性, 當(dāng)副作用執(zhí)行完成后它會獲取到要觸發(fā)的 Action 對象并觸發(fā)這個(gè) Action // Actions // 當(dāng)組件觸發(fā) Action 時(shí), Effect 需要通過 Actions 服務(wù)接收 Action, 所以在 Effect 類中通過 constructor 構(gòu)造函數(shù)參數(shù)的方式將 Actions 服務(wù)類的實(shí)例對象注入到 Effect 類中 // Actions 服務(wù)類的實(shí)例對象為 Observable 對象, 當(dāng)有 Action 被觸發(fā)時(shí), Action 對象本身會作為數(shù)據(jù)流被發(fā)出 // ofType // 對目標(biāo) Action 對象進(jìn)行過濾. // 參數(shù)為目標(biāo) Action 的 Action Creator 函數(shù) // 如果未過濾出目標(biāo) Action 對象, 本次不會繼續(xù)發(fā)送數(shù)據(jù)流 // 如果過濾出目標(biāo) Action 對象, 會將 Action 對象作為數(shù)據(jù)流繼續(xù)發(fā)出 @Injectable() export class CounterEffects { constructor(private actions: Actions) { // this.loadCount.subscribe(console.log) } loadCount = createEffect(() => { return this.actions.pipe( ofType(increment_async), mergeMap(() => timer(1000).pipe(map(() => increment({ count: 10 })))) ) }) }
Entity
##1、概述Entity 譯為實(shí)體,實(shí)體就是集合中的一條資料。
NgRx 中提供了實(shí)體適配器對象,在實(shí)體適配器物件下面提供了各種操作集合中實(shí)體的方法,目的就是提高開發(fā)者操作實(shí)體的效率。
2、核心##1、EntityState:實(shí)體類型介面
/* { ids: [1, 2], entities: { 1: { id: 1, title: "Hello Angular" }, 2: { id: 2, title: "Hello NgRx" } } } */ export interface State extends EntityState<Todo> {}2、createEntityAdapter: 建立實(shí)體適配器物件3、EntityAdapter:實(shí)體適配器物件類型介面
export const adapter: EntityAdapter<Todo> = createEntityAdapter<Todo>() // 獲取初始狀態(tài) 可以傳遞對象參數(shù) 也可以不傳 // {ids: [], entities: {}} export const initialState: State = adapter.getInitialState()#3、實(shí)例方法
##https://ngrx.io /guide/entity/adapter#adapter-collection-methods
#4、選擇器
##
// selectTotal 獲取數(shù)據(jù)條數(shù) // selectAll 獲取所有數(shù)據(jù) 以數(shù)組形式呈現(xiàn) // selectEntities 獲取實(shí)體集合 以字典形式呈現(xiàn) // selectIds 獲取id集合, 以數(shù)組形式呈現(xiàn) const { selectIds, selectEntities, selectAll, selectTotal } = adapter.getSelectors();
export const selectTodo = createFeatureSelector<AppState, State>(todoFeatureKey) export const selectTodos = createSelector(selectTodo, selectAll)#Router Store
1、同步路由狀態(tài)
1)引入模組import { StoreRouterConnectingModule } from "@ngrx/router-store"
@NgModule({
imports: [
StoreRouterConnectingModule.forRoot()
]
})
export class AppModule {}
2)將路由狀態(tài)整合到Store
import * as fromRouter from "@ngrx/router-store" export interface AppState { router: fromRouter.RouterReducerState } export const reducers: ActionReducerMap<AppState> = { router: fromRouter.routerReducer }2、建立取得路由狀態(tài)的Selector
// router.selectors.ts import { createFeatureSelector } from "@ngrx/store" import { AppState } from ".." import { RouterReducerState, getSelectors } from "@ngrx/router-store" const selectRouter = createFeatureSelector<AppState, RouterReducerState>( "router" ) export const { // 獲取和當(dāng)前路由相關(guān)的信息 (路由參數(shù)、路由配置等) selectCurrentRoute, // 獲取地址欄中 # 號后面的內(nèi)容 selectFragment, // 獲取路由查詢參數(shù) selectQueryParams, // 獲取具體的某一個(gè)查詢參數(shù) selectQueryParam('name') selectQueryParam, // 獲取動態(tài)路由參數(shù) selectRouteParams, // 獲取某一個(gè)具體的動態(tài)路由參數(shù) selectRouteParam('name') selectRouteParam, // 獲取路由自定義數(shù)據(jù) selectRouteData, // 獲取路由的實(shí)際訪問地址 selectUrl } = getSelectors(selectRouter)
// home.component.ts import { select, Store } from "@ngrx/store" import { AppState } from "src/app/store" import { selectQueryParams } from "src/app/store/selectors/router.selectors" export class AboutComponent { constructor(private store: Store<AppState>) { this.store.pipe(select(selectQueryParams)).subscribe(console.log) } }更多程式相關(guān)知識,請?jiān)煸L:程式設(shè)計(jì)影片! !
以上是angular學(xué)習(xí)之詳解狀態(tài)管理器NgRx的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣圖片

Undresser.AI Undress
人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6
視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Angular.js是一種可自由存取的JavaScript平臺,用於建立動態(tài)應(yīng)用程式。它允許您透過擴(kuò)展HTML的語法作為模板語言,以快速、清晰地表示應(yīng)用程式的各個(gè)方面。 Angular.js提供了一系列工具,可協(xié)助您編寫、更新和測試程式碼。此外,它還提供了許多功能,如路由和表單管理。本指南將討論在Ubuntu24上安裝Angular的方法。首先,您需要安裝Node.js。 Node.js是一個(gè)基於ChromeV8引擎的JavaScript運(yùn)行環(huán)境,可讓您在伺服器端執(zhí)行JavaScript程式碼。要在Ub

angular中怎麼使用monaco-editor?以下這篇文章記錄下最近的一次業(yè)務(wù)中用到的 m??onaco-editor 在 angular 中的使用,希望對大家有幫助!

隨著網(wǎng)路的快速發(fā)展,前端開發(fā)技術(shù)也不斷改進(jìn)與迭代。 PHP和Angular是兩種廣泛應(yīng)用於前端開發(fā)的技術(shù)。 PHP是一種伺服器端腳本語言,可以處理表單、產(chǎn)生動態(tài)頁面和管理存取權(quán)限等任務(wù)。而Angular是一種JavaScript的框架,可以用來開發(fā)單一頁面應(yīng)用程式和建構(gòu)元件化的網(wǎng)頁應(yīng)用程式。本篇文章將介紹如何使用PHP和Angular進(jìn)行前端開發(fā),以及如何將它們

這篇文章帶大家繼續(xù)angular的學(xué)習(xí),簡單了解一下Angular中的獨(dú)立組件(Standalone Component),希望對大家有幫助!

這篇文章帶大家深入了解angular的狀態(tài)管理器NgRx,介紹一下NgRx的使用方法,希望對大家有幫助!

你知道 Angular Universal 嗎?可以幫助網(wǎng)站提供更好的 SEO 支援哦!

身份驗(yàn)證是任何網(wǎng)路應(yīng)用程式中最重要的部分之一。本教程討論基於令牌的身份驗(yàn)證系統(tǒng)以及它們與傳統(tǒng)登入系統(tǒng)的差異。在本教程結(jié)束時(shí),您將看到一個(gè)用Angular和Node.js編寫的完整工作演示。傳統(tǒng)身份驗(yàn)證系統(tǒng)在繼續(xù)基於令牌的身份驗(yàn)證系統(tǒng)之前,讓我們先來看看傳統(tǒng)的身份驗(yàn)證系統(tǒng)。使用者在登入表單中提供使用者名稱和密碼,然後點(diǎn)擊登入。發(fā)出請求後,透過查詢資料庫在後端驗(yàn)證使用者。如果請求有效,則使用從資料庫中獲取的使用者資訊建立會話,然後在回應(yīng)頭中傳回會話訊息,以便將會話ID儲存在瀏覽器中。提供用於存取應(yīng)用程式中受

Angular框架中元件的預(yù)設(shè)顯示行為不是區(qū)塊級元素。這種設(shè)計(jì)選擇促進(jìn)了元件樣式的封裝,並鼓勵開發(fā)人員有意識地定義每個(gè)元件的顯示方式。透過明確設(shè)定CSS屬性 display,Angular組件的顯示可以完全控制,從而實(shí)現(xiàn)所需的佈局和響應(yīng)能力。
