博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[AngularJS NG-redux] Handle Asynchronous Operations with Middleware
阅读量:5134 次
发布时间:2019-06-13

本文共 2045 字,大约阅读时间需要 6 分钟。

Invariably the question that comes up when talking about Redux is how does one handle asynchronous operations in redux. For instance, how do we hand off an operation to redux that requires a remote call to the server? Where exactly does the async part get handled?

Redux has this concept of middleware that allows us to insert custom logic in the space between dispatching an action, and the moment it reaches the reducer. In this lesson, we are going to set up a few async operations and then use redux thunk middleware to make sure that everything makes it into the reducer properly.

The main key to thunk middleware is that it allows us to return a function instead of an action. This function can encapsulate the async operation and dispatches the appropriate action when the operation is completed.

 

To handle async opreations, we can install:

npm install --save redux-thunk

 

Import:

import thunk from 'redux-thunk';

 

Use it as middle ware:

const config = $ngReduxProvider => {  'ngInject';  $ngReduxProvider.createStoreWith(rootReducers, [thunk]);};

 

Refactor action creator to use thunk middleware:

export const CategoriesActions = ($http, $q) => {  'ngInject';  const FETCH = {    categories: 'data/categories.json'  };  /*const getCategoreis = (categories) => {   return {type: GET_CATEGORIES, payload: categories}   };*/  const getCategoreis = () => {    return (dispatch, getState) => {      const { categories } = getState();      if (categories.length > 0) {        return $q.when(categories);      } else {        return $http.get(FETCH.categories)          .then(res => res.data)          .then((payload) => {            return dispatch({              type: GET_CATEGORIES,              payload            })          });      }    };  };....}

Here we use cache, so we need to set initial value to empty array:

export const categories = (state = [], { type, payload }) => {  switch (type) {    case GET_CATEGORIES:      return payload || state;    default:      return state;  }};

 

转载于:https://www.cnblogs.com/Answer1215/p/6063339.html

你可能感兴趣的文章
Assets和Raw区别
查看>>
【luogu4185】 [USACO18JAN]MooTube [并查集]
查看>>
手机号脱敏处理
查看>>
CI控制器调用内部方法并载入相应模板的做法
查看>>
Hdu - 1002 - A + B Problem II
查看>>
HDU - 2609 - How many
查看>>
每天CookBook之Python-003
查看>>
每天CookBook之Python-004
查看>>
Android设置Gmail邮箱
查看>>
StringBuffer的用法
查看>>
js编写时间选择框
查看>>
PHP压缩文件操作
查看>>
4.你认为一些军事方面的软件系统采用什么样的开发模型比较合适?
查看>>
日常开发需要掌握的Maven知识
查看>>
Java数据结构和算法(四)--链表
查看>>
JIRA
查看>>
ssl介绍以及双向认证和单向认证原理
查看>>
【BZOJ2441】【中山市选2011】小W的问题(树状数组+权值线段树)
查看>>
小技巧——直接在目录中输入cmd然后就打开cmd命令窗口
查看>>
深浅拷贝(十四)
查看>>