额外的 NgRx 库
让我们来了解一下 NgRx 提供的其他库。
在本课程中,我们已经学习了以下 NgRx 库:
@ngrx/store@ngrx/effects@ngrx/store-devtools
接下来我们简要了解一些其他的 NgRx 库。
@ngrx/router-store 库
在 Angular 应用中进行页面跳转时,我们经常需要完成以下任务:
-
在导航之前、之后或过程中执行某些操作。
-
偶尔需要在页面之间传递数据。
-
有时需要从 URL 中提取查询参数。
通过使用 @ngrx/router-store 库,我们可以简化这些复杂逻辑。
@ngrx/component-store 库
使用 @ngrx/store 可以管理整个应用的状态。但如果我们希望高效地管理单个组件的状态,可以借助 @ngrx/component-store 库。
@ngrx/store 与 @ngrx/component-store 之间的一个主要区别在于:@ngrx/store 将整个应用的状态保存在一个单一的状态对象中,而 @ngrx/component-store 则为每个组件维护独立的状态。
@ngrx/entity 库
在使用 @ngrx/store 时,我们在每个模块中几乎都编写了相同结构的 reducer 和 selector 代码。
src/app/products/state/products.reducers.ts
1import { createReducer, on } from "@ngrx/store"; 2import { loadProductsAction, getProductsAction, getErrorAction } from "./products.actions"; 3import { ProductsState } from "./products.interfaces"; 4import { productsInitialState } from "./products.state"; 5 6export const productsReducer = createReducer<ProductsState>( 7 productsInitialState, 8 on(getProductsAction, (state, { products }): ProductsState => [ ...products ]), 9 on(loadProductsAction, (state): ProductsState => { 10 return [ ...state ]; 11 }), 12 on(getErrorAction, (state): ProductsState => { 13 return [ ...state ]; 14 }) 15)
src/app/product/state/product.reducers.ts
1import { createReducer, on } from "@ngrx/store"; 2import { getProductAction } from "./product.actions"; 3import { ProductState } from "./product.interfaces"; 4import { productInitialState } from "./product.state"; 5 6export const productReducer = createReducer<ProductState>( 7 productInitialState, 8 on(getProductAction, (state, { id }): ProductState => +id) 9)
通过使用 @ngrx/entity 库,我们可以几乎完全避免这种重复代码。
@ngrx/data 库
尽管 @ngrx/entity 能帮助我们减少 reducer 和 selector 的重复代码,但它无法解决动作(actions)、分发器(dispatchers)以及数据获取逻辑(如 HTTP GET、PUT、POST、DELETE 等)的重复问题。这时我们可以使用 @ngrx/data 来解决这一问题。
@ngrx/schematics 库
由于 NgRx 的功能遵循特定的文件夹结构,如果能有一个工具快速生成项目结构将非常方便。@ngrx/schematics 库通过提供 CLI 命令解决了这个问题。只需运行相应的命令,即可快速创建包含动作、reducer、selector 等 NgRx 功能的项目结构。
@ngrx/eslint-plugin 库
该库帮助我们检测最常见的 NgRx 错误。它内置了针对 @ngrx/store、@ngrx/effects 和 @ngrx/component-store 的预设规则,使我们能够更高效地维护 NgRx 代码。