发送多个异步HTTP GET请求 [英] Send multiple asynchronous HTTP GET requests

查看:132
本文介绍了发送多个异步HTTP GET请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个API调用,我需要多次调用,因为该API不支持对多个项目的请求.到目前为止,我所写的内容最终陷入了向服务器发送GET请求的无休止的循环中.我相信在以下示例中我不了解Observables的本质.我的假设是,while循环中的每个调用都预订了一个新的单个对象,当它解析后将被放置在数组中.如何修改下面的代码以实现我想要的?

I've got an API call that I need to make multiple times as the API doesn't support requests for multiple items. What I have written so far ends up in an endless loop of sending GET requests to the server. I believe I don't understand the nature of Observables in the below example. My assumption is that each call in the while loop subscribes to a new single object and that when it is resolved it will be placed in the array. How can I modify the below code to achieve what I want?

getSingle(): Observable<Single> {
    return this.http.get(this.url, this.options)
     .map((r: Response) => r.json().data as Single);
}

getMultiple(num: number): Single[] {
    let multiple: Single[] = [];

    let i = 0;
    while (i < num) {
        this.getSingle().subscribe(single => {
            multiple.push(single);
            console.log('Success');
            i++;
        }, err => {
            console.log('Failure');
        });
   }

   return multiple;
}

推荐答案

应避免使用while循环发出多个异步HTTP请求,然后分别订阅所有这些请求,以免出现许多Observable连接已打开.我们可以使用 Observable.forkJoin 运算符.

Using the while loop to make multiple asynchronous HTTP requests, and then subscribe to all of them separately should be avoided in order not to have many Observable connections opened. We can use Observable.forkJoin operator instead.

这是实现的样子:

getSingle(singleUrl: string): Observable<Single> {
    return this.http.get(singleUrl, this.options)
        .map((r: Response) => r.json().data as Single);
};

getMultiple(): Observable<Array<Single>> {
    let singleUrls = ['singleUrl1', 'singleUrl2', 'singleUrl3']; // can be replaced with any 'Single' identifier

    let singleObservables = singleUrls.map((singleUrl: string, urlIndex: number) => {
        return this.getSingle(singleUrl)
            .map(single => single as Single)
            .catch((error: any) => {
                console.error('Error loading Single, singleUrl: ' + singleUrl, 'Error: ', error);
                return Observable.of(null); // In case error occurs, we need to return Observable, so the stream can continue
            });
    });

    return Observable.forkJoin(singleObservables);
};

this.getMultiple().subscribe(
    (singles: Array<Single>) => {
        console.log(singles); // [Single, Single, Single];
        // In case error occured e.g. for the 'singleUrl' (our 'Single' identifier) at position 1,
        // Output wil be: [Single, null, Single];
    }
);

希望这会有所帮助!

这篇关于发送多个异步HTTP GET请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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