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 ?
Why use forkJoin ? This operator is best used when you have a group of observables and only care about the final emitted value of each. One common use case for this is if you wish to issue multiple requests on page load (or some other event) and only want to take action when a response has been received for all.
On clicking on tabs you interchange state and you use ngOnInit() method every time when a state is changed to get the data.In this way, you can reduce API calls by using nested routing.
HttpRequest represents an outgoing request, including URL, method, headers, body, and other request configuration options. Instances should be assumed to be immutable. To modify a HttpRequest , the clone method should be used.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With