Angular2:动态同步 http 请求 [英] Angular2: Dynamic synchronous http requests

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

问题描述

目标:发出一系列同步 http 请求,并能够将它们作为一个可观察流订阅.

Goal: To make a series of synchronous http requests and be able to subscribe to them as one observable stream.

示例(不起作用):

let query_arr = ['test1','test2','test3']

function make_request(query_arr){

    if (query_arr.length){

        let payload = JSON.stringify(query_arr[0]);
        let headers = new Headers();

        query_arr.splice(0,1);

        this.http.post('https://endpoint/post',payload,{headers:headers})
            .map((res:Response) => {make_request(query_arr)})

    }

}.subscribe(
    data => console.log('finished http request, moving on to next http request'),
    err => console.error(err),
    () => console.log('all http requests have been finished')
);

make_request(query_arr)

目标功能:

  • 需要知道每个响应何时返回
  • 必须知道所有响应何时返回

推荐答案

您需要利用 flatMap 运算符来依次(一个接一个)执行您的请求.为此,您需要递归地构建数据处理链.这里的重点是在前一个 observable(前一个请求返回的那个)上调用操作符.

You need to leverage the flatMap operator to execute your requests in series (one after one). For this, you need to build your data processing chain recursively. The point here is to call the operator on the previous observable (the one returned by the previous request).

这样请求会等待前一个完成后再执行.订阅时提供的回调会在所有请求执行完毕后调用.

This way the request will wait for the previous one to be complete before executed itself. The callback provided when subscribing will be called when all requests were executed.

以下是此方法的示例实现:

Here is a sample implementation of this approach:

makeRequest(queryArr, previousObservable){
  if (queryArr.length) {
    let payload = JSON.stringify(queryArr[0]);
    let headers = new Headers();
    (...)

    queryArr.splice(0,1);

    var observable = null;
    if (previousObservable) {
      observable = previousObservable.flatMap(() => {
        return this.http.post('https://testsoapi.apispark.net/v1/entities', payload,{
            headers:headers
          })
          .map((res:Response) => res.json())
          .do(() => {
            console.log('request finished');
          });
      });
    } else {
      observable = this.http.post('https://testsoapi.apispark.net/v1/entities', payload, {
        headers:headers
      })
        .map((res:Response) => res.json())
        .do(() => {
          console.log('request finished');
        });
    }

    return this.makeRequest(queryArr, observable);
  } else {
    return previousObservable;
  }
}

这个方法最初可以这样调用:

This method can be called initially like this:

test() {
  let queryArr = [
    { val: 'test1' },
    { val: 'test2' },
    { val: 'test3' }
  ];

  this.makeRequest(queryArr).subscribe(
    () => {
      console.log('all requests finished');
    });
}

查看此 plunkr:https://plnkr.co/edit/adtWwckvhwXJgPDgCurQ?p=preview.

See this plunkr: https://plnkr.co/edit/adtWwckvhwXJgPDgCurQ?p=preview.

这篇关于Angular2:动态同步 http 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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