NgRx Store is mainly for managing global state across an entire application. In cases where you need to manage temporary or local component state, consider using NgRx ComponentStore.

NgRx Store是为了管理整个应用的全局状态而设计的,如果想管理局部Component状态或者临时状态,请使用NgRx ComponentStore.

Actions are the inputs and outputs of many systems in NgRx.

Actions是NgRx系统的输入和输出。

NgRx里标准的Action interface:

export interface Action {type: string;
}

NgRx reducer的immutability特性

Each action handles the state transition immutably. This means that the state transitions are not modifying the original state, but are returning a new state object using the spread operator. The spread syntax copies the properties from the current state into the object, creating a new reference.

状态迁移并不会修改原始状态,而是借助三个点 … 即spread操作符,返回新的state对象。Spread 操作符会从当前state变量里拷贝属性,生成新的对象引用。

const scoreboardReducer = createReducer(initialState,on(ScoreboardPageActions.homeScore, state => ({ ...state, home: state.home + 1 })),on(ScoreboardPageActions.awayScore, state => ({ ...state, away: state.away + 1 })),on(ScoreboardPageActions.resetScore, state => ({ home: 0, away: 0 })),on(ScoreboardPageActions.setScores, (state, { game }) => ({ home: game.home, away: game.away }))
);export function reducer(state: State | undefined, action: Action) {return scoreboardReducer(state, action);
}

When an action is dispatched, all registered reducers receive the action. Whether they handle the action is determined by the on functions that associate one or more actions with a given state change.

The state of your application is defined as one large object.

Registering reducer functions to manage parts of your state only defines keys with associated values in the object. To register the global Store within your application, use the StoreModule.forRoot() method with a map of key/value pairs that define your state.

The StoreModule.forRoot() registers the global providers for your application, including the Store service you inject into your components and services to dispatch actions and select pieces of state.

StoreModule.forRoot 为应用注册全局的服务提供者,包括注入到Component里的Store服务,以及用于dispatch actions的service以及选择state片段的服务。

Registering states with StoreModule.forRoot() ensures that the states are defined upon application startup. In general, you register root states that always need to be available to all areas of your application immediately.

使用StoreModule.forRoot注册的states,在应用startup之后立即处于可用状态。如果一个state在应用启动后,需要迅速被应用各个部分使用,那么需要注册成root state.

feature state

Feature states behave in the same way root states do, but allow you to define them with specific feature areas in your application. Your state is one large object, and feature states register additional keys and values in that object.

下面的代码,给应用注册了一个空的root state:

import { NgModule } from '@angular/core';
import { StoreModule } from '@ngrx/store';@NgModule({imports: [StoreModule.forRoot({})],
})
export class AppModule {}

feature module的注册方法:

import { NgModule } from '@angular/core';
import { StoreModule } from '@ngrx/store';
import * as fromScoreboard from './reducers/scoreboard.reducer';@NgModule({imports: [StoreModule.forFeature(fromScoreboard.scoreboardFeatureKey, fromScoreboard.reducer)],
})
export class ScoreboardModule {}

只要在app.module.ts里将包含了上述feature state的module import,就能做到feature state的eager import:

import { NgModule } from '@angular/core';
import { StoreModule } from '@ngrx/store';
import { ScoreboardModule } from './scoreboard/scoreboard.module';@NgModule({imports: [StoreModule.forRoot({}),ScoreboardModule],
})
export class AppModule {}

selector

Selectors are pure functions used for obtaining slices of store state.

纯函数,唯一作用就是获得store state的片段数据。

Selectors provide many features when selecting slices of state:

  • Portability
  • Memoization
  • Composition
  • Testability
  • Type Safety

When using the createSelector and createFeatureSelector functions @ngrx/store keeps track of the latest arguments in which your selector function was invoked.

使用createSelector和createFeatureSelector之后,ngRx框架代码会记录当我们的selector被调用时,传入的输入参数。这么做的动机是,selectors是纯函数,因此相同的输入一定会产生相同的输出,所以ngRx把每次输入以及输出都缓存起来,如果下次调用selector的输入在缓存里有记录,即从缓存里返回输出数据,以提高性能。

这种行为称为memoization.

下图的代码,调用createFeatureSelector传入一个字符串,创建一个feature selector:

返回类型为MemoizedSelector,即带有记忆功能的selector.

createSelector的输入参数,以及返回的类型仍然是selector:

createSelector支持传入多达8个selector,来实现更复杂的取数逻辑。看个例子:

The createSelector function can take up to 8 selector functions for more complete state selections.

For example, imagine you have a selectedUser object in the state. You also have an allBooks array of book objects.
And you want to show all books for the current user.

import { createSelector } from '@ngrx/store';export interface User {id: number;name: string;
}export interface Book {id: number;userId: number;name: string;
}export interface AppState {selectedUser: User;allBooks: Book[];
}export const selectUser = (state: AppState) => state.selectedUser;
export const selectAllBooks = (state: AppState) => state.allBooks;export const selectVisibleBooks = createSelector(selectUser,selectAllBooks,(selectedUser: User, allBooks: Book[]) => {if (selectedUser && allBooks) {return allBooks.filter((book: Book) => book.userId === selectedUser.id);} else {return allBooks;}}
);

The createFeatureSelector is a convenience method for returning a top level feature state. It returns a typed selector function for a feature slice of state.

更多Jerry的原创文章,尽在:“汪子熙”:

NgRx Store里的StoreModule.forRoot()相关推荐

  1. 从ngrx store里selector出来的Observable,执行subscribe的单步调试

    源代码: getNextPageContext(): Observable<PageContext> {const a = this.store.pipe(select(RoutingSe ...

  2. Angular Ngrx store 里的 Selector 介绍

    选择器是纯函数,它将状态切片(State slice)作为输入参数,并返回组件可以使用的状态数据切片(这些切片包含真正的业务数据). 正如数据库有自己的 SQL 查询语言一样,Ngrx/store 模 ...

  3. NgRx Store createSelector 返回的 selector 执行取数逻辑的单步调试

    测试源代码: import { Component } from '@angular/core'; import { createSelector } from '@ngrx/store';expor ...

  4. NgRx store.dispatch方法的单步调试

    this.store.dispatch方法执行之后,会触发哪些操作呢? _value里维护的store的初始值: store里有三个字段: actionsObserver reducerManager ...

  5. 关于 @ngrx/Store 下 obj 的扩展问题

    为什么80%的码农都做不了架构师?>>>    昨天做 task 的时候,遇到了一个问题. TypeError: can't define property "x" ...

  6. NgRx Store createSelector 的单步调试和源代码分析

    源代码: import { Component } from '@angular/core'; import { createSelector } from '@ngrx/store';export ...

  7. vue3 实现监听store里state状态变化

    vue3 实现监听store里state状态变化 import { watch } from "vue"; watch(() => store.state.currentDe ...

  8. 教大家如何方便地用百度代理装国外ovi store里的软件--页面不会跳来跳去

    原贴 http://bbs.dospy.com/thread-6034274-1-1.html 教大家如何方便地用百度代理装国外ovi store里的软件--页面不会跳来跳去 国外OVI store有 ...

  9. iPhone在App Store里下载应用很慢解决方法

    由于苹果在中国没有部署服务器,以及一些线路问题,导致中国大陆用户从苹果App Store中下载应用程序非常缓慢,如果网络条件不是很好的用户,往往只有10多KB/S的速度,一般2M的ADSL只有三四十K ...

最新文章

  1. Ruby中的多行注释?
  2. 队列实现栈的3种方法,全都击败了100%的用户!
  3. vue watch的监听
  4. linux 常见开机故障解决办法
  5. android第十二步Pull解析器解析和生成XML内容
  6. 博士论文答辩||基于深度强化学习的复杂作业车间调度问题研究
  7. eclipse 点击 ctrl+鼠标左键看不了源码问题解决
  8. 汉诺塔递归算法(Python编程)
  9. 南阳oj 57题------6174问题
  10. 大陆、港澳台身份证、护照、军官证、户口本的正则表达式
  11. 我的世界服务器被无限循环怎么办,我的世界无限循环装置制作方法
  12. border-style之double实现三道杠
  13. Week_eight
  14. ROS1云课-导航实践测评
  15. 【如何3秒钟看出一个人的python实力|Python 数据分析打怪升级之路 day04】:手把手教你如何分析用户数据、数据分析基本概念
  16. 获取平面的法向量_艾孜尔江撰
  17. 摄影测量学期末复习总结
  18. matplotlib的默认字体_matplotlib中中文字体配置
  19. html傻瓜式制作软件,云梦html制作工具(html傻瓜式制作)
  20. 3.4-注意缺陷多动障碍儿童

热门文章

  1. Mybatis基于XML配置SQL映射器(二)
  2. JavaSE 学习参考:变量(1)
  3. 自动装箱与拆箱引发的享元设计模式
  4. JFinal 1.1.4 发布,JAVA极速WEB+ORM框架
  5. 5.4. Interaction Between Devices and Kernel 设备与内核的交互
  6. mcse 2000 认证介绍
  7. 整理 | 软件与工具的收集汇总及推荐
  8. 什么是Shell,Shell教程
  9. 尚硅谷_JS DOM编程_学习笔记
  10. 最简单的网络图片的爬取 --Pyhon网络爬虫与信息获取