Penjelasan terperinci tentang pengurus keadaan pembelajaran sudut NgRx

青灯夜游
Lepaskan: 2022-05-25 11:01:20
ke hadapan
2567 orang telah melayarinya

Artikel ini akan memberi anda pemahaman yang mendalam tentang pengurus negeri angular, dan memperkenalkan cara menggunakan NgRx, saya harap ia akan membantu semua orang.

Penjelasan terperinci tentang pengurus keadaan pembelajaran sudut NgRx

NgRx ialah penyelesaian seni bina Redux untuk pengurusan keadaan global dalam aplikasi Angular. [Cadangan tutorial berkaitan: "tutorial sudut"]

Penjelasan terperinci tentang pengurus keadaan pembelajaran sudut NgRx

  • @ngrx/store: Modul pengurusan negeri global

  • @ngrx/effects: Kendalikan kesan sampingan

  • @ngrx/store-devtools: Alat nyahpepijat penyemak imbas, perlu bergantung pada Redux Devtools Extension

  • @ngrx/schematics: Alat baris perintah untuk menjana fail NgRx dengan pantas

  • @ngrx/entity: Meningkatkan kecekapan pembangun mengendalikan data dalam Reducer

  • @ngrx/router-store: Segerakkan status laluan ke Kedai global

Mula Pantas

1. Muat turun NgRx

npm install @ngrx/store @ngrx/effects @ngrx/entity @ngrx/router-store @ngrx/store-devtools @ngrx/schematics

2 Konfigurasikan NgRx CLI

ng config cli.defaultCollection @ngrx/schematics

// angular.json
"cli": {
  "defaultCollection": "@ngrx/schematics"
}
Salin selepas log masuk
<. 🎜>

3. Cipta Kedai

ng g store State --root --module app.module.ts --statePath store --stateInterface AppState

4 🎜>5. Cipta Peredam

ng g action store/actions/counter --skipTests

import { createAction } from "@ngrx/store"

export const increment = createAction("increment")
export const decrement = createAction("decrement")
Salin selepas log masuk

6 🎜>

ng g reducer store/reducers/counter --skipTests --reducers=../index.ts

7 Kelas komponen mencetuskan Tindakan dan mendapat status
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 }))
)
Salin selepas log masuk

8

ng g selector store/selectors/counter --skipTests

Beban Tindakan
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)
Salin selepas log masuk

1. Lulus parameter apabila menggunakan penghantaran dalam komponen untuk mencetuskan Tindakan, dan parameter akhirnya akan diletakkan dalam objek Tindakan.

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())
  }
}
Salin selepas log masuk
2. Apabila mencipta fungsi Pencipta Tindakan, dapatkan parameter dan nyatakan jenis parameter.

3. Dapatkan parameter melalui objek Action dalam Reducer.
<button (click)="increment()">+</button>
<span>{{ count | async }}</span>
<button (click)="decrement()">-</button>
Salin selepas log masuk

MetaReducer

metaReducer ialah cangkuk antara Action -> Reducer, membenarkan pembangun untuk mempraproses Action (dipanggil sebelum panggilan fungsi Reducer biasa).
this.store.dispatch(increment({ count: 5 }))
Salin selepas log masuk

import { createAction, props } from "@ngrx/store"
export const increment = createAction("increment", props<{ count: number }>())
Salin selepas log masuk
Kesan
export declare function props<P extends object>(): Props<P>;
Salin selepas log masuk

Keperluan: Tambahkan butang pada halaman dan tangguhkan satu saat selepas mengklik butang untuk membenarkan nilai meningkat.
export const reducer = createReducer(
  initialState,
  on(increment, (state, action) => ({ count: state.count + action.count }))
)
Salin selepas log masuk

1. Tambah butang untuk peningkatan nilai tak segerak dalam templat komponen Selepas butang diklik, kaedah dilaksanakan

2 🎜> kaedah, dan pencetus Tindakan

function debug(reducer: ActionReducer<any>): ActionReducer<any> {
  return function (state, action) {
    return reducer(state, action)
  }
}

export const metaReducers: MetaReducer<AppState>[] = !environment.production
  ? [debug]
  : []
Salin selepas log masuk

yang melakukan operasi tak segerak dalam kaedah 3. Tambah Tindakan

yang melakukan operasi tak segerak dalam fail Tindakan . Terima Tindakan dan lakukan kesan sampingan, teruskan mencetuskan Tindakan

increment_async

Fungsi kesan disediakan oleh modul @ngrx/effects, jadi kebergantungan modul yang berkaitan perlu diimport dalam akar modul
<button (click)="increment_async()">async</button>
Salin selepas log masuk

increment_async

Entiti
increment_async() {
  this.store.dispatch(increment_async())
}
Salin selepas log masuk

export const increment_async = createAction("increment_async")
Salin selepas log masuk

1. Gambaran Keseluruhan

ng g effect store/effects/counter --root --module app.module.ts --skipTests

Entiti diterjemahkan sebagai entiti, dan entiti ialah sekeping data dalam koleksi .

NgRx menyediakan objek penyesuai entiti Di bawah objek penyesuai entiti, pelbagai kaedah untuk mengendalikan entiti dalam koleksi disediakan.
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
// 用于创建 Effect, Effect 用于执行副作用.
// 调用方法时传递回调函数, 回调函数中返回 Observable 对象, 对象中要发出副作用执行完成后要触发的 Action 对象
// 回调函数的返回值在 createEffect 方法内部被继续返回, 最终返回值被存储在了 Effect 类的属性中
// NgRx 在实例化 Effect 类后, 会订阅 Effect 类属性, 当副作用执行完成后它会获取到要触发的 Action 对象并触发这个 Action

// Actions
// 当组件触发 Action 时, Effect 需要通过 Actions 服务接收 Action, 所以在 Effect 类中通过 constructor 构造函数参数的方式将 Actions 服务类的实例对象注入到 Effect 类中
// Actions 服务类的实例对象为 Observable 对象, 当有 Action 被触发时, Action 对象本身会作为数据流被发出

// ofType
// 对目标 Action 对象进行过滤.
// 参数为目标 Action 的 Action Creator 函数
// 如果未过滤出目标 Action 对象, 本次不会继续发送数据流
// 如果过滤出目标 Action 对象, 会将 Action 对象作为数据流继续发出

@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 }))))
    )
  })
}
Salin selepas log masuk

2. Teras

1.EntityState: Antara muka jenis entiti

2 Objek

3. EntityAdapter: Antara Muka Jenis Objek Penyesuai Entiti

3 Kaedah Contoh

https:/ /ngrx.io/guide/entity/adapter#adapter-collection-methods

/*
	{
		ids: [1, 2],
		entities: {
			1: { id: 1, title: "Hello Angular" },
			2: { id: 2, title: "Hello NgRx" }
		}
	}
*/
export interface State extends EntityState<Todo> {}
Salin selepas log masuk

4 Pemilih

export const adapter: EntityAdapter<Todo> = createEntityAdapter<Todo>()
// 获取初始状态 可以传递对象参数 也可以不传
// {ids: [], entities: {}}
export const initialState: State = adapter.getInitialState()
Salin selepas log masuk

<. 🎜>Stor Penghala

1 Segerakkan status penghalaan

1) Import modul

// selectTotal 获取数据条数
// selectAll 获取所有数据 以数组形式呈现
// selectEntities 获取实体集合 以字典形式呈现
// selectIds 获取id集合, 以数组形式呈现
const { selectIds, selectEntities, selectAll, selectTotal } = adapter.getSelectors();
Salin selepas log masuk
2. ) Integrasikan status penghalaan ke dalam Stor
export const selectTodo = createFeatureSelector<AppState, State>(todoFeatureKey)
export const selectTodos = createSelector(selectTodo, selectAll)
Salin selepas log masuk

2. Cipta Pemilih untuk mendapatkan status penghalaan

Kemas kini Untuk lebih pengetahuan berkaitan pengaturcaraan, sila layari:

Video Pengaturcaraan

! !
import { StoreRouterConnectingModule } from "@ngrx/router-store"

@NgModule({
  imports: [
    StoreRouterConnectingModule.forRoot()
  ]
})
export class AppModule {}
Salin selepas log masuk

Atas ialah kandungan terperinci Penjelasan terperinci tentang pengurus keadaan pembelajaran sudut NgRx. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
sumber:csdn.net
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!