【发布时间】:2016-11-10 05:10:31
【问题描述】:
我在 Angular 2 中使用 ng-redux 模块,但我不知道执行异步操作的更好方法是什么。例如,我需要从服务器获取一些数据。我可以使用异步操作创建者redux-thunk 中间件来做到这一点: 我将创建一个返回函数的操作:
export function fetchData() {
return function (dispatch) {
dispatch({
type: 'FETCH_DATA_REQUEST'
});
return fetch(url)
.then(response => response.json())
.then(json => dispatch({type: 'FETCH_DATA_SUCCESS', data: json}))
.catch(error => dispatch({type: 'FETCH_DATA_ERROR', error: error
}
}
}
dispatch(fetchData());
或者我可以在控制器中做HTTP请求,我将手动执行调度方法:
dispatch({
type: 'FETCH_DATA_REQUEST'
});
http(url).then(data => {
dispatch({
type: 'FETCH_DATA_SUCCESS',
data: json
});
}).catch(error => {
dispatch({
type: 'FETCH_DATA_ERROR',
error: error
});
});
推荐哪种方法?我认为第二种方法更容易,但是为什么会有 redux-thunk 中间件。
【问题讨论】: