Home >Web Front-end >JS Tutorial >Angular uses ngrx/store for state management
This article will introduce to you the use of Angular ngrx/store state management. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Related tutorial recommendations: "angular Tutorial"
Using ngrx for state management in Angular
Introduction
ngrx/store is inspired by Redux and is an Angular state management library integrated with RxJS. Developed by Angular evangelist Rob Wormald. It has the same core idea as Redux, but uses RxJS to implement the observer pattern. It follows the core Redux principles but is designed specifically for Angular.
Most of the state management in Angular can be taken over by service. In some medium and large projects, the disadvantages of this will be revealed. One of them is that the state flow is chaotic, which is not conducive to later maintenance. Later, It draws on the state management model of redux and combines it with the characteristics of rxjs flow programming to form @ngrx/store, a state management tool for Angular.
StoreModule:
StoreModule is a module in @ngrx/store API, which is used to configure reducers in application modules.
Action:
Action is a change in state. It describes the occurrence of an event, but does not specify how the application's state changes.
Store:
It provides Store.select() and Store.dispatch() to work with the reducer. Store.select() is used to select a selector,
Store.dispatch(
{
type:'add',
payload:{name:'111'}
}
)
The type used to distribute actions to reducers.
Three principles of @NgRx/Store state management
First of all, @NgRx/Store also adheres to Redux’s Three basic principles:
This principle is that the state of the entire single-page application is stored in the store in the form of an object tree.
This definition is very abstract. In fact, it is to store all the data that needs to be shared in the form of javascript objects.
state = { application:'angular app', shoppingList:['apple', 'pear'] }
One of the core features of ngrx/store is that users cannot directly modify the status content. For example, if we need to save the status of the login page, the status information needs to record the name of the logged in user. When the login name changes, we cannot directly modify the user name saved in the state
state={'username':'kat'}, //用户重新登录别的账户为tom state.username = 'tom' //在ngrx store 这个行为是绝对不允许的
Because The state cannot be changed directly. ngrx/store also introduces a concept called reducer (aggregator). Modify the state through the reducer.
function reducer(state = 'SHOW_ALL', action) { switch (action.type) { case 'SET_VISIBILITY_FILTER': return Object.assign({}, state ,newObj); default: return state } }
ngrx/store usage example
1. Install @ngrx/store
yarn add @ngrx/store
2. Create state, action, reducer
state state:
app\store\state.ts
//下面是使用接口的情况, 更规范 export interface TaskList { id: number; text: string; complete: boolean; } export const TASKSAll: TaskList[] = [ {id: 1, text: 'Java Article 1', complete: false}, {id: 2, text: 'Java Article 2', complete: false} ] export interface AppState { count: number; todos: TaskList; // 如果要管理多个状态,在这个接口中添加即可 } //这个是不用接口的情况 // export interface AppState { // count: number; // todos: any; // // 如果要管理多个状态,在这个接口中添加即可 // }
reducer
app\store\reducer.ts
// reducer.ts,一般需要将state,action,reducer进行文件拆分 import { Action } from '@ngrx/store'; export const INCREMENT = 'INCREMENT'; export const DECREMENT = 'DECREMENT'; export const RESET = 'RESET'; const initialState = 0; // reducer定义了action被派发时state的具体改变方式 export function counterReducer(state: number = initialState, action: Action) { switch (action.type) { case INCREMENT: return state + 1; case DECREMENT: return state - 1; case RESET: return 0; default: return state; } }
actions
If you need to extract the action separately Come out, refer to
5 below. What should I do if I want to separate the action?
3. Register store
Root module:
app/app.module.ts
import { NgModule } from '@angular/core'; import { StoreModule } from '@ngrx/store'; // StoreModule: StoreModule是@ngrx/storeAPI中的一个模块, // 它被用来在应用模块中配置reducer。 import {counterReducer} from './store/reducer'; @NgModule({ imports: [ StoreModule.forRoot({ count: counterReducer }), // 注册store ], }) export class AppModule {}
4. Use store
Inject the store into the component or service for use
Take the app\module\article\article.component.ts component as an example:
// 组件级别 import { Component } from '@angular/core'; import { Store, select } from '@ngrx/store'; import { Observable } from 'rxjs'; import { INCREMENT, DECREMENT, RESET} from '../../store/reducer'; interface AppState { count: number; } @Component({ selector: 'app-article', templateUrl: './article.component.html', styleUrls: ['./article.component.css'] }) export class ArticleComponent { count: Observable<number>; constructor(private store: Store<AppState>) { // 注入store this.count = store.pipe(select('count')); // 从app.module.ts中获取count状态流 } increment() { this.store.dispatch({ type: INCREMENT }); } decrement() { this.store.dispatch({ type: DECREMENT }); } reset() { this.store.dispatch({ type: RESET }); } }
Template page:
app\module\article\article.component.html
<div class="state-count"> <button (click)="increment()">增加Increment</button> <div>Current Count: {{ count | async }}</div> <button (click)="decrement()">减少Decrement</button> <button (click)="reset()">Reset Counter</button> </div>
The pipe symbol async is used here, and an error will be reported directly if it is used directly in the sub-module. If two-way binding of data is to be implemented in the sub-module, an error will also be reported. , for specific reasons, please refer to the question explained in the courseware: The pipe 'async' could not be found?
How to render the page without using pipes in the template page?
Modify as follows:
count: Observable<number>; constructor(private store: Store<AppState>) { // 注入store var stream = store.pipe(select('count')); // 从app.module.ts中获取count状态流 stream.subscribe((res)=>{ this.count = res; }) }
For the convenience of management, type, state, actions, reducers are generally managed separately
5 What to do if you want to separate actions?
import { Injectable } from '@angular/core'; import { INCREMENT, DECREMENT, RESET } from './types'; @Injectable() export class CounterAction{ // Add=function(){} Add(){ return { type: INCREMENT } } } // 就只这样导出是不行的 // export function Add1(){ // return { type: INCREMENT } // }
import {CounterAction} from './store/actions'; ... providers: [CounterAction],
import {CounterAction} from '../../store/actions'; export class ArticleComponent implements OnInit { constructor( private action: CounterAction //注入CounterAction ) { } increment() { // this.store.dispatch({ type: INCREMENT }); //把 actions分离出去 this.store.dispatch(this.action.Add()); } }
For more programming-related knowledge, please visit: Programming Learning! !
The above is the detailed content of Angular uses ngrx/store for state management. For more information, please follow other related articles on the PHP Chinese website!