在 redux-observable 中使用 fetch 而不是 ajax [英] Use fetch instead of ajax with redux-observable

查看:20
本文介绍了在 redux-observable 中使用 fetch 而不是 ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

redux-observable 中是否可以使用 isomporphic-fetch 而不是 Rx.DOM.ajax?

In redux-observable is it possible to use isomporphic-fetch instead of Rx.DOM.ajax?

推荐答案

(注意:RX.DOM.ajax 来自 RxJS v4,不能与redux-observable 需要 RxJS v5.v5 中的等价物是 Rx.Observable.ajaximport { ajax } from 'rxjs/observable/ajax';)

(Note: RX.DOM.ajax is from RxJS v4, and doesn't work with redux-observable which requires RxJS v5. The equivalent in v5 is Rx.Observable.ajax or import { ajax } from 'rxjs/observable/ajax';)

确实可以使用 fetch() 以及任何其他 AJAX API;尽管有些人比其他人更容易适应!

It is indeed possible to use fetch() as well as any other AJAX API; though some adapt easier than others!

fetch() API 返回一个 Promise,RxJS v5 具有内置支持.大多数期望 observable 的操作符可以按原样使用 Promises(例如 mergeMapswitchMap 等).但是通常您会希望在将 Promise 传递给 Epic 的其余部分之前将 Rx 运算符应用于 Promise,因此您通常希望将 Promise 包装在 Observable 中.

The fetch() API returns a Promise, which RxJS v5 has built-in support for. Most operators that expect an observable can consume Promises as-is (like mergeMap, switchMap, etc). But often you'll want to apply Rx operators to the Promise before passing it along to the rest of your Epic, so you'll often want to wrap the Promise inside an Observable.

您可以使用 Observable.from(promise)

这是一个示例,我为用户获取数据,请求 JSON 响应,然后将承诺包装在 observable 中:

Here's an example where I fetch for a user, request the JSON response, then wrap the promise in an observable:

const api = {
  fetchUser: id => {
    const request = fetch(`https://jsonplaceholder.typicode.com/users/${id}`)
      .then(response => response.json());
    return Observable.from(request);
  }
};

然后您可以在 Epic 中使用它并应用您想要的任何运算符:

You can then consume that in your Epic and apply any operators you want:

const fetchUserEpic = action$ =>
  action$.ofType(FETCH_USER)
    .mergeMap(action =>
      api.fetchUser(action.payload) // This returns our Observable wrapping the Promise
        .map(payload => ({ type: FETCH_USER_FULFILLED, payload }))
    );

这是一个带有这个工作示例的 JSBin:https://jsbin.com/fuwaguk/edit?js,输出

Here's a JSBin with this working example: https://jsbin.com/fuwaguk/edit?js,output

如果您可以控制 API 代码,理想情况下您会使用 Observable.ajax(或任何其他基于 Observable 的 AJAX 实用程序),因为无法取消承诺.(截至撰写本文时)

If you have control over the API code, ideally you would use Observable.ajax (or any other Observable-based AJAX utils) because Promises cannot be cancelled. (as of this writing)

这篇关于在 redux-observable 中使用 fetch 而不是 ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆