search
HomeWeb Front-endJS TutorialAngular uses ngrx/store for state management

Angular uses ngrx/store for state management

Jan 21, 2021 pm 05:21 PM
angularStatus 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.

Angular uses ngrx/store for state management

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:

  • 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 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(&#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, 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(&#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 What to do if you want 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 '../../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!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software