Angular 2 Http, Observables and recursive requests
<p>I have a REST endpoint that returns a list of items, max 1000 items at a time. If there are more than 1000 items, the response has HTTP status 206 and there's a <code>Next-Range</code> header that I can use in my next request for getting more items.</p>

<p>I'm working on <strong>an Angular 2 application</strong> and trying to implement this with <code>Http</code> and <code>Observable</code>. My problem is that I don't know <strong>how to merge multiple <code>Observable</code>s</strong> depending on how many pages of items there are and <strong>finally return one <code>Observable</code></strong> that my component can subscribe to.</p>

<p>Here's where I've got with my current TypeScript implementation:</p>

<pre class="lang-js prettyprint-override"><code>// NOTE: Non-working example!

getAllItems(): Observable&lt;any[]&gt; {
  // array of all items, possibly received with multiple requests
  const allItems: any[] = [];

  // inner function for getting a range of items
  const getRange = (range?: string) =&gt; {
    const headers: Headers = new Headers();
    if (range) {
      headers.set('Range', range);
    }

    return this.http.get('http://api/endpoint', { headers })
      .map((res: Response) =&gt; {
        // add all to received items
        // (maybe not needed if the responses can be merged some other way?)
        allItems.push.apply(allItems, res.json());

        // partial content
        if (res.status === 206) {
          const nextRange = res.headers.get('Next-Range');

          // get next range of items
          return getRange(nextRange);
        }

        return allItems;
      });
  };

  // get first range
  return getRange();
}
</code></pre>

<p>However, this doesn't work. If I understood it correctly, an <code>Observable</code> is returned as the value of the initial <code>Observable</code> and not the array of items.</p>