Angular&Redux-effectsormultipleactionsinreducers
创始人
2024-10-21 01:00:11
0

使用ngrx/effects库实现数据副作用,并在reducers中使用多个action处理状态更新。

在Angular应用中使用ngrx库可以方便地管理状态。在一些情况下需要处理异步操作或副作用,此时可以使用ngrx/effects库。

以一个简单的例子为例,假设我们需要从服务器获取一个列表并在应用中显示。首先,我们创建一个actions.ts文件定义对应的Action和ActionType:

import { Action } from '@ngrx/store';

export enum ListActionTypes {
  LOAD_LIST = '[List] Load List',
  LOAD_LIST_SUCCESS = '[List] Load List Success',
  LOAD_LIST_FAILURE = '[List] Load List Failure'
}

export class LoadList implements Action {
  readonly type = ListActionTypes.LOAD_LIST;
}

export class LoadListSuccess implements Action {
  readonly type = ListActionTypes.LOAD_LIST_SUCCESS;
  constructor(public payload: any[]) {}
}

export class LoadListFailure implements Action {
  readonly type = ListActionTypes.LOAD_LIST_FAILURE;
  constructor(public payload: string) {}
}

export type ListActions = LoadList | LoadListSuccess | LoadListFailure;

在effects.ts文件中定义ListEffects类,使用HttpClient从服务器获取数据:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { of } from 'rxjs';

import * as ListActions from './actions';

@Injectable()
export class ListEffects {
  constructor(private actions$: Actions, private http: HttpClient) {}

  loadList$ = createEffect(() =>
    this.actions$.pipe(
      ofType(ListActions.ListActionTypes.LOAD_LIST),
      mergeMap(() =>
        this.http.get('https://your-server-url/list').pipe(
          map(data => new ListActions.LoadListSuccess(data)),
          catchError(error => of(new ListActions.LoadListFailure(error)))
        )
      )
    )
  );
}

在reducer中定义对应的处理函数:

import * as ListActions from './actions';

export interface State {
  list: any[];
  loading: boolean;
  error: string;

相关内容

热门资讯

普及透视!wepoker私人局... 普及透视!wepoker私人局俱乐部辅助,wepoker黑侠辅助器,都是存在有辅助软件(哔哩哔哩)在...
推荐透视!德普之星透视,德普之... 推荐透视!德普之星透视,德普之星有透视辅助吗,切实有辅助脚本(哔哩哔哩)1、操作简单,无需手机版透视...
教你透视!aapoker透视脚... 教你透视!aapoker透视脚本,aapoker插件下载,好像一直总是有辅助攻略(哔哩哔哩)1、辅助...
关于透视!wpk透视辅助靠谱吗... 关于透视!wpk透视辅助靠谱吗,wpk透视是真的吗,切实是有辅助攻略(哔哩哔哩)所有人都在同一条线上...
普及透视!aapoker俱乐部... 普及透视!aapoker俱乐部靠谱吗,aapoker俱乐部靠谱吗,真是真的是有辅助方法(哔哩哔哩)1...
科普透视!hhpoker脚本下... 科普透视!hhpoker脚本下载,hhpoker辅助软件,总是真的是有辅助脚本(哔哩哔哩)该软件可以...
解迷透视!hhpkoer辅助挂... 解迷透视!hhpkoer辅助挂是真的吗,hhpoker可以控制牌吗,一直真的有辅助脚本(哔哩哔哩)1...
科普透视!hhpoker怎么开... 科普透视!hhpoker怎么开透视,hhpoker脚本下载,原来一直都是有辅助工具(哔哩哔哩)运辅助...
必备透视!hhpoker辅助挂... 必备透视!hhpoker辅助挂,hhpoker买挂,其实存在有辅助教程(哔哩哔哩)1、下载好正确养号...
了解透视!aapoker透视插... 了解透视!aapoker透视插件,aapoker辅助器是真的吗,果然真的有辅助插件(哔哩哔哩)辅助器...