国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Action Payload
MetaReducer
Effect
Home Web Front-end JS Tutorial Detailed explanation of angular learning state manager NgRx

Detailed explanation of angular learning state manager NgRx

May 25, 2022 am 11:01 AM
angular angular.js

This article will give you an in-depth understanding of angular's state manager NgRx, and introduce how to use NgRx. I hope it will be helpful to everyone!

Detailed explanation of angular learning state manager NgRx

NgRx is a Redux architecture solution for global state management in Angular applications. [Related tutorial recommendations: "angular tutorial"]

Detailed explanation of angular learning state manager NgRx

  • ##@ngrx/store: Global state management module

  • @ngrx/effects: Handling side effects

  • @ngrx/store-devtools: Browser debugging tool, needs to rely on Redux Devtools Extension

  • @ngrx/schematics: Command line tool to quickly generate NgRx files

  • @ngrx/entity: Improve the efficiency of developers operating data in Reducer

  • @ngrx/router-store: Synchronize routing status to the global Store

Quick start

1. Download NgRx

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

2. Configure NgRx CLI

ng config cli.defaultCollection @ngrx/schematics

// angular.json
"cli": {
  "defaultCollection": "@ngrx/schematics"
}

3. Create Store

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

4 , create Action

ng g action store/actions/counter --skipTests

import { createAction } from "@ngrx/store"

export const increment = createAction("increment")
export const decrement = createAction("decrement")

5, create 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. Create 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. Component class triggers Action and gets status

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. Component template display status

<button (click)="increment()">+</button>
<span>{{ count | async }}</span>
<button (click)="decrement()">-</button>

Action Payload

1. Use dispatch in the component to pass parameters when triggering Action, and the parameters will eventually be placed in Action object.

this.store.dispatch(increment({ count: 5 }))

2. When creating the Action Creator function, obtain the parameters and specify the parameter type.

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

3. Get parameters through Action object in Reducer.

export const reducer = createReducer(
  initialState,
  on(increment, (state, action) => ({ count: state.count + action.count }))
)

MetaReducer

metaReducer is a hook between Action -> Reducer, allowing developers to preprocess Action (called before ordinary Reducer function calls).

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

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

Effect

Requirement: Add a button to the page, and after clicking the button, delay for one second to increase the value.

1. Add a button for asynchronous value increment in the component template. After the button is clicked, the

increment_async method

<button (click)="increment_async()">async</button>

2. Add a new button in the component class Add the

increment_async method, and trigger the Action

increment_async() {
  this.store.dispatch(increment_async())
}

in the method to perform the asynchronous operation. 3. Add the Action

export const increment_async = createAction("increment_async")

to the Action file. 4. Create Effect, receive Action and perform side effects, continue to trigger Action

ng g effect store/effects/counter --root --module app.module.ts --skipTests## The #Effect function is provided by the @ngrx/effects module, so the relevant module dependencies need to be imported in the root module

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 對(duì)象, 對(duì)象中要發(fā)出副作用執(zhí)行完成后要觸發(fā)的 Action 對(duì)象
// 回調(diào)函數(shù)的返回值在 createEffect 方法內(nèi)部被繼續(xù)返回, 最終返回值被存儲(chǔ)在了 Effect 類的屬性中
// NgRx 在實(shí)例化 Effect 類后, 會(huì)訂閱 Effect 類屬性, 當(dāng)副作用執(zhí)行完成后它會(huì)獲取到要觸發(fā)的 Action 對(duì)象并觸發(fā)這個(gè) Action

// Actions
// 當(dāng)組件觸發(fā) Action 時(shí), Effect 需要通過(guò) Actions 服務(wù)接收 Action, 所以在 Effect 類中通過(guò) constructor 構(gòu)造函數(shù)參數(shù)的方式將 Actions 服務(wù)類的實(shí)例對(duì)象注入到 Effect 類中
// Actions 服務(wù)類的實(shí)例對(duì)象為 Observable 對(duì)象, 當(dāng)有 Action 被觸發(fā)時(shí), Action 對(duì)象本身會(huì)作為數(shù)據(jù)流被發(fā)出

// ofType
// 對(duì)目標(biāo) Action 對(duì)象進(jìn)行過(guò)濾.
// 參數(shù)為目標(biāo) Action 的 Action Creator 函數(shù)
// 如果未過(guò)濾出目標(biāo) Action 對(duì)象, 本次不會(huì)繼續(xù)發(fā)送數(shù)據(jù)流
// 如果過(guò)濾出目標(biāo) Action 對(duì)象, 會(huì)將 Action 對(duì)象作為數(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, OverviewEntity is translated as entity, and entity is a piece of data in the collection.

NgRx provides entity adapter objects. Under the entity adapter objects, various methods for operating entities in the collection are provided. The purpose is to improve the efficiency of developers operating entities.

2. Core1. EntityState: Entity type interface

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

2. createEntityAdapter: Create entity adapter object

3. EntityAdapter: Entity Adapter Object Type Interface

export const adapter: EntityAdapter<Todo> = createEntityAdapter<Todo>()
// 獲取初始狀態(tài) 可以傳遞對(duì)象參數(shù) 也可以不傳
// {ids: [], entities: {}}
export const initialState: State = adapter.getInitialState()

3. Instance Methodhttps://ngrx.io /guide/entity/adapter#adapter-collection-methods

4. Selector

// 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();
rrree

Router Store

1. Synchronize routing status1)Introduce module

export const selectTodo = createFeatureSelector<AppState, State>(todoFeatureKey)
export const selectTodos = createSelector(selectTodo, selectAll)

2)Integrate routing status into Store

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

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

2. Create a Selector to obtain routing status

import * as fromRouter from "@ngrx/router-store"

export interface AppState {
  router: fromRouter.RouterReducerState
}
export const reducers: ActionReducerMap<AppState> = {
  router: fromRouter.routerReducer
}
// 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,
  // 獲取地址欄中 # 號(hào)后面的內(nèi)容
  selectFragment,
  // 獲取路由查詢參數(shù)
  selectQueryParams,
  // 獲取具體的某一個(gè)查詢參數(shù) selectQueryParam(&#39;name&#39;)
  selectQueryParam,
  // 獲取動(dòng)態(tài)路由參數(shù)
  selectRouteParams,
 	// 獲取某一個(gè)具體的動(dòng)態(tài)路由參數(shù) selectRouteParam(&#39;name&#39;)
  selectRouteParam,
  // 獲取路由自定義數(shù)據(jù)
  selectRouteData,
  // 獲取路由的實(shí)際訪問(wèn)地址
  selectUrl
} = getSelectors(selectRouter)
For more programming-related knowledge, please visit:

Programming Video

! !

The above is the detailed content of Detailed explanation of angular learning state manager NgRx. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

Angular learning talks about standalone components (Standalone Component) Angular learning talks about standalone components (Standalone Component) Dec 19, 2022 pm 07:24 PM

This article will take you to continue learning angular and briefly understand the standalone component (Standalone Component) in Angular. I hope it will be helpful to you!

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

Do you know Angular Universal? It can help the website provide better SEO support!

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

What should I do if the project is too big? How to split Angular projects reasonably? What should I do if the project is too big? How to split Angular projects reasonably? Jul 26, 2022 pm 07:18 PM

The Angular project is too large, how to split it reasonably? The following article will introduce to you how to reasonably split Angular projects. I hope it will be helpful to you!

See all articles