在redux可观察的epic中为ajax响应发出两个动作的方法如下:
import { ofType } from 'redux-observable';
import { mergeMap } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';
const myEpic = (action$, state$) =>
action$.pipe(
ofType('FETCH_DATA'), // 替换成你的action类型
mergeMap(action => {
return ajax.getJSON('https://api.example.com/data').pipe(
mergeMap(response => [
{ type: 'FETCH_DATA_SUCCESS', payload: response }, // 替换成你的成功动作类型和payload
{ type: 'ANOTHER_ACTION', payload: response } // 替换成你的另一个动作类型和payload
]),
catchError(error => {
// 处理错误情况
console.error('Error:', error);
return of({ type: 'FETCH_DATA_ERROR', payload: error }); // 替换成你的错误动作类型和payload
})
);
})
);
export default myEpic;
import { combineEpics } from 'redux-observable';
import myEpic from './myEpic';
const rootEpic = combineEpics(
myEpic
);
export default rootEpic;
import { createStore, applyMiddleware } from 'redux';
import { createEpicMiddleware } from 'redux-observable';
import rootReducer from './reducers';
import rootEpic from './epics';
const epicMiddleware = createEpicMiddleware();
const store = createStore(
rootReducer,
applyMiddleware(epicMiddleware)
);
epicMiddleware.run(rootEpic);
export default store;
现在,当你的应用程序触发一个FETCH_DATA动作时,redux-observable将会执行myEpic函数。该函数将发起一个ajax请求,并在成功和失败时分别发出两个动作。你可以根据需要替换动作类型和payload。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云