5

I'm making a simple app with Angular 4 & an API who has several pages for their requests.

For example I get the 10 first characters with this url : http://swapi.co/api/people/

And to get the next 10 people I have to make request to this url : http://swapi.co/api/people/?page=2

How can I get all people in one request ? Or what is the solution to make all requests with good practices ?

4
  • @jonrsharpe why deleting the code and when I'm saying 'thanks' ? Commented Jul 15, 2017 at 11:32
  • Because including an answer and saying 'thanks' isn't a question. See stackoverflow.com/help/someone-answers for appropriate things to do when your question gets answered. Commented Jul 15, 2017 at 11:34
  • I thought the code could help people in this case. And the "thank by advance" means thanks for people who will work on this problem, it was not related to an answer. But ok Commented Jul 15, 2017 at 11:43
  • Just a comment, but shouldn't the data be loaded async on page change? Commented May 14, 2018 at 12:12

1 Answer 1

14

You have to use forkJoin method in order to load data from more than one source.

First of all, include them in the typescript file.

import {Observable} from 'rxjs/Rx';

UPDATE

For new versions of Angular use this:

import { forkJoin } from 'rxjs';

Many times, we need to load data from more than one source, and we need to wait until all the data has loaded.

forkJoin method wraps multiple Observables. In the other words, we use forkJoin to run concurrent http requests.

subscribe() method of forkJoin sets the handlers on the entire set of Observables.

You can read more about forkJoin here, including a lot of examples.

Suppose you have to get first 10 pages.

var pages:number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

Or simply: var pages:number[] = new Array(10).fill().map((v, i) => i + 1);

// map them into a array of observables and forkJoin
return Observable.forkJoin(
   pages.map(
      i => this.http.get('http://swapi.co/api/people/?page=' + i)
        .map(res => res.json())
   )
).subscribe(people => this.people = people);
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for your answer. I edited my question with your suggestions.
@QuentinIcky, the mistake is that you use second map method wrong. Second map method is attached to the this.http.get... (like in my answer)
Thanks that's right! I edited the question with the new code. I don't get any error, but now the people disappear from the view. How can I log the response and use the data to the component file ?
@QuentinIcky, I found the mistake.. use return Observable.forkJoin instead Observable.forkJoin
Well done ! I understood that it was a return issue but I didn't found where ! Thanks al lot for your help!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.