Home>Article>Web Front-end> Using ngrx/store for state management in Angular
ngrx/store is inspired by Redux and is an Angular state management library integrated with RxJS. It was 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.
Recommended related tutorials: "Angular tutorial》
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.
First of all, @NgRx/Store also adheres to the three basic principles of Redux:
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 } }
yarn add @ngrx/store
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, please refer to the following
5 What to do if you want to separate the action?
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 {}
in a component or service Inject into the store 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; constructor(private store: Store ) { // 注入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
Current Count: {{ count | async }}
The pipe symbol async is used here. If you use it directly in the sub-module, an error will be reported. If you want to implement two-way binding of data in the sub-module, an error will also be reported. For the specific reasons, please refer to the issue 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; constructor(private store: Store ) { // 注入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
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:Introduction to Programming! !
The above is the detailed content of Using ngrx/store for state management in Angular. For more information, please follow other related articles on the PHP Chinese website!