关于angular:Angular-Ngrx-Store-工具库里-Action-定义指南

3次阅读

共计 1304 个字符,预计需要花费 4 分钟才能阅读完成。

Store 文件夹数据结构的一个典型例子:

当您第一次应用 ngrx/store 模块时,必须决定运行应用程序所需的操作。首先剖析从服务器端加载 Heroes 数据的过程并决定应该进行哪些 Action 建模。

  • 从服务器端加载所有英雄数据,因而须要一个加载英雄的动作。
  • 一个 Effect 启动并从服务器端检索英雄数据。Effect 还须要告诉 Store 咱们曾经胜利地检索到了 Heroes 数据,因而它须要调度一个动作(Load Heroes Success Action)。如果与服务器端的通信失败或出于任何其余起因,Effect 会调度另一个动作(加载英雄失败)进行错误处理。

Ngrx Store 提供的 Action 接口:

export interface Action {type: string;}

咱们创立一些字符串常量,作为 Action 的标识:

export const LOAD_HEROES = "[Heroes] Load Heroes";
export const LOAD_HEROES_FAIL = "[Heroes] Load Heroes Fail";
export const LOAD_HEROES_SUCCESS = "[Heroes] Load Heroes Success";

其中 [] 中括号,代表 Action 的类型 -category.

而后咱们就有了很多 Action Class:

export class LoadHeroes implements Action {readonly type = LOAD_HEROES;}

export class LoadHeroesFail implements Action {
    readonly type = LOAD_HEROES_FAIL;

    // can pass any error from server-side
    constructor(public payload: any) {}}

export class LoadHeroesSuccess
    implements Action {
        readonly type = LOAD_HEROES_SUCCESS;
        constructor(public payload: fromCore.Hero[])
{}}

每个动作类都定义了一个类型属性,因为它实现了 Action 接口。此外,在某些状况下,须要在自定义 Action 类上定义一个可选的无效负载属性,以便调度此操作的代码能够传入一些额定的数据,这些数据稍后会被 Reducer 用来组成新的状态。

LoadHeroesFail 操作类定义了一个无效负载属性来保留与服务器端通信期间抛出的异样的主体。

相似地,LoadHeroesSuccess 动作类定义了一个无效负载属性,来保留从服务器端检索到的理论英雄数据并将其传递给 Reducer.

最初,因为应用 TypeScript 开发 Angular 应用程序,您能够通过定义一个新的 TypeScript 类型(称为 HeroesAction 类型)来增加一些动作类型查看,以保留下面定义的所有动作类。这样,reducer 只解决在此类型上定义的操作。

export type HeroesAction =
    | LoadHeroes
    | LoadHeroesFail
    | LoadHeroesSuccess;
正文完
 0