如何在 TypeScript 的 ReactiveX/rxjs 5 中使用exhaustMap [英] How to use exhaustMap in ReactiveX/rxjs 5 in TypeScript

查看:17
本文介绍了如何在 TypeScript 的 ReactiveX/rxjs 5 中使用exhaustMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何处理一个数组,其中每个值都按照指定的顺序返回一个 Promise.例如,假设我想按以下顺序调用多个 Ajax 调用:

I was wondering how can I process an array where each value returns a Promise in the same order as they're specified. For example, let's say I want to call multiple Ajax calls in this order:

var array = [
    'http://example.org',
    'http://otherexample.org',
    'http://anotherexample.org',
];

基本上有同样的问题:如何使用 RxJs 推迟对 AJAX 调用的任何请求,直到前一个请求解决,这建议使用 flatMapFirst.

There's basicaly the same question: How can I use RxJs to hold off any requests for an AJAX call until the previous one resolves, which suggests using flatMapFirst.

由于我在使用 rxjs@5.0.0-beta.2 的 TypeScript 中使用 Angular2(此时 beta-15),我发现 flatMapFirst 已重命名为 exhaustMap.

Since I'm using Angular2 (beta-15 at this moment) in TypeScript which uses rxjs@5.0.0-beta.2 I found out that flatMapFirst has been renamed to exhaustMap.

但是这个操作符没有列在 Observable.ts,因此我不能使用它.它甚至不存在于 RxJS https://code 的捆绑版本中.angularjs.org/2.0.0-beta.15/Rx.js.

But this operator isn't listed in Observable.ts, therefore I can't use it. It's not even present in the bundled version of RxJS https://code.angularjs.org/2.0.0-beta.15/Rx.js.

那么,我应该如何使用它?或者有没有其他方法可以满足我的需要?它的 package.json 列出了很多构建脚本,我应该强制它使用其中之一吗?

So, how am I supposed to use it? Or is there any other way to the what I need? Its package.json lists a lot of build scripts, should I force it to use one of them?

我应该提到我使用的是 ReactiveX/rxjs 库,而不是 Reactive-Extensions/RxJS

I should mention I'm using ReactiveX/rxjs library, not Reactive-Extensions/RxJS

推荐答案

运算符 concatMap() 完成了这项工作:

Operator concatMap() did the job:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/concatMap';

var urls = [
  'https://httpbin.org/get?1',
  'https://httpbin.org/get?2',
  'https://httpbin.org/get?3',
  'https://httpbin.org/get?4',
  'https://httpbin.org/get?5',
];     

Observable.from(this.urls)
  .concatMap(url => http.get(url))
  .subscribe(response => console.log(response.url))
;

这会打印到控制台:

https://httpbin.org/get?1
https://httpbin.org/get?2
https://httpbin.org/get?3
https://httpbin.org/get?4
https://httpbin.org/get?5

这篇关于如何在 TypeScript 的 ReactiveX/rxjs 5 中使用exhaustMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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