Home  >  Article  >  Web Front-end  >  A brief discussion on how to use ngrx for state management in Angular

A brief discussion on how to use ngrx for state management in Angular

青灯夜游
青灯夜游forward
2021-03-01 10:54:233226browse

A brief discussion on how to use ngrx for state management in Angular

Related recommendations: "angular Tutorial"

ngrx/store is inspired by Redux and is an Angular state management library that integrates 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 streaming 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 the three basic principles of Redux:

  • Single data source

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']
}
  • state is read-only (the state can only be in read-only form)

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 这个行为是绝对不允许的
  • changes are made with pure functions (the state can only be changed by calling functions)

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, please refer to the following
5 If you want to separate the action How to deal with it when it comes out?

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: Observabled80b5def5ed1be6e26d91c2709f14170;

  constructor(private store: Store6076dd82de29ad27bc912ad957f38fdd) { // 注入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

a29455b745944c9a0d8e3afc470893ae

    6cfdf2a3cab4a4f728db77c1a4b50ad0增加Increment65281c5ac262bf6d81768915a4a77ac0
    dc6dce4a544fdca2df29d5ac0ea9906bCurrent Count: {{ count | async }}16b28748ea4df4d9c2150843fecfba68
    6a5a5a8f92e6df93009eca891f03f025减少Decrement65281c5ac262bf6d81768915a4a77ac0

    dd9bc48600714170fea322b8a3484257Reset Counter65281c5ac262bf6d81768915a4a77ac0
16b28748ea4df4d9c2150843fecfba68

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: Observabled80b5def5ed1be6e26d91c2709f14170;

constructor(private store: Store6076dd82de29ad27bc912ad957f38fdd) { // 注入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 If How to separate actions?

  1. Create a new \app\store\actions.ts file
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 }
// }
  1. Register in the root module app.module.ts
import {CounterAction} from './store/actions';

... 

providers: [CounterAction],
  1. Used in components – article.component.ts
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 Video! !

The above is the detailed content of A brief discussion on how to use ngrx for state management in Angular. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete