Angular 2 - 链接 http 请求 [英] Angular 2 - Chaining http requests

查看:28
本文介绍了Angular 2 - 链接 http 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 httpService 获得了一个 RxJS Observable,它是来自 Angular 的实际 http.现在,一旦我从中得到肯定的结果,我就想处理从 this.retrieve() 获得的下一个 http 请求.这或多或少是串联请求.有更好的方法吗?

I get a RxJS Observable from an httpService which is the actual http from Angular. Now as soon as I get a postive result from that, I want to process the next http Request which I get from this.retrieve(). This is more or less concattening requests. Is there a better way of doing it?

return this.httpService.query(data) 
        .map(data => {
            if(data.status > 1)
               this.retrieve().subscribe();
            return data;
});

推荐答案

链接 HTTP 请求可以使用 flatMapswitchMap 操作符来完成.假设我们要发出三个请求,其中每个请求都取决于前一个请求的结果:

Chaining HTTP requests can be done using flatMap or switchMap operators. Say we want to make three requests where each request depends on the result of previous one:

this.service.firstMethod()
    .flatMap(firstMethodResult => this.service.secondMethod(firstMethodResult))
    .flatMap(secondMethodResult => this.service.thirdMethod(secondMethodResult))
    .subscribe(thirdMethodResult => {
          console.log(thirdMethodResult);
     });

通过这种方式,您可以链接尽可能多的相互依赖的请求.

This way you can chain as much interdependent requests you want.

更新:从 RxJS 5.5 版开始引入可管道操作符,语法略有变化:

UPDATE: As of RxJS version 5.5 pipeable operators were introduced and the syntax has slightly changed:

import {switchMap, flatMap} from 'rxjs/operators';

this.service
  .firstMethod()
  .pipe(
    switchMap(firstMethodResult => this.service.secondMethod(firstMethodResult)),
    switchMap(secondMethodResult => this.service.thirdMethod(secondMethodResult))
  )
  .subscribe(thirdMethodResult => {
      console.log(thirdMethodResult);
    });

这篇关于Angular 2 - 链接 http 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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