search
HomeWeb Front-endJS TutorialUsing ngrx/store for state management in Angular
Using ngrx/store for state management in AngularSep 15, 2020 am 10:28 AM
angularStatus management

Using ngrx/store for state management in Angular

Introduction

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.

@NgRx/Store Three principles of 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 What to do if you 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

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<number>;

  constructor(private store: Store<AppState>) { // 注入store
    this.count = store.pipe(select(&#39;count&#39;)); 
    // 从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. 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<number>;

constructor(private store: Store<AppState>) { // 注入store
    var stream = store.pipe(select(&#39;count&#39;)); 
    // 从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 &#39;@angular/core&#39;;
import { INCREMENT, DECREMENT, RESET } from &#39;./types&#39;;

@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 &#39;./store/actions&#39;;

... 

providers: [CounterAction],
  1. Used in components – article.component.ts
import {CounterAction} from &#39;../../store/actions&#39;;

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!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
聊聊Angular中的元数据(Metadata)和装饰器(Decorator)聊聊Angular中的元数据(Metadata)和装饰器(Decorator)Feb 28, 2022 am 11:10 AM

本篇文章继续Angular的学习,带大家了解一下Angular中的元数据和装饰器,简单了解一下他们的用法,希望对大家有所帮助!

angular学习之详解状态管理器NgRxangular学习之详解状态管理器NgRxMay 25, 2022 am 11:01 AM

本篇文章带大家深入了解一下angular的状态管理器NgRx,介绍一下NgRx的使用方法,希望对大家有所帮助!

浅析angular中怎么使用monaco-editor浅析angular中怎么使用monaco-editorOct 17, 2022 pm 08:04 PM

angular中怎么使用monaco-editor?下面本篇文章记录下最近的一次业务中用到的 monaco-editor 在 angular 中的使用,希望对大家有所帮助!

Angular + NG-ZORRO快速开发一个后台系统Angular + NG-ZORRO快速开发一个后台系统Apr 21, 2022 am 10:45 AM

本篇文章给大家分享一个Angular实战,了解一下angualr 结合 ng-zorro 如何快速开发一个后台系统,希望对大家有所帮助!

项目过大怎么办?如何合理拆分Angular项目?项目过大怎么办?如何合理拆分Angular项目?Jul 26, 2022 pm 07:18 PM

Angular项目过大,怎么合理拆分它?下面本篇文章给大家介绍一下合理拆分Angular项目的方法,希望对大家有所帮助!

聊聊自定义angular-datetime-picker格式的方法聊聊自定义angular-datetime-picker格式的方法Sep 08, 2022 pm 08:29 PM

怎么自定义angular-datetime-picker格式?下面本篇文章聊聊自定义格式的方法,希望对大家有所帮助!

浅析Angular中的独立组件,看看怎么使用浅析Angular中的独立组件,看看怎么使用Jun 23, 2022 pm 03:49 PM

本篇文章带大家了解一下Angular中的独立组件,看看怎么在Angular中创建一个独立组件,怎么在独立组件中导入已有的模块,希望对大家有所帮助!

聊聊Angular Route中怎么提前获取数据聊聊Angular Route中怎么提前获取数据Jul 13, 2022 pm 08:00 PM

Angular Route中怎么提前获取数据?下面本篇文章给大家介绍一下从 Angular Route 中提前获取数据的方法,希望对大家有所帮助!

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version