使用fetch代替redux-observable的ajax [英] Use fetch instead of ajax with redux-observable

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

问题描述

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

推荐答案

(注意: RX.DOM.ajax 来自RxJS v4 ,不适用于 redux-observable ,它需要 RxJS v5 。v5中的等效项是 Rx.Observable.ajax 从'rxjs / observable / ajax'导入{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具有内置支持。大多数期望可观察到的运算符可以按原样使用Promises(例如 mergeMap switchMap 等)。但是通常您会希望先将Rx运算符应用于Promise,然后再将其传递给Epic的其余部分,因此,您通常会希望将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)

You can wrap a Promise into an Observable with Observable.from(promise)

在此示例中,我为用户获取信息,请求JSON响应,然后将诺言包装在可观察到的地方:

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,output

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

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

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)

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

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