I\'m having a hard time wrapping my brain around observables in Angular. I\'m coming from the world of PHP, where things are definitely not async.
I have a componen
In fact, Reactive Programming allows to create asynchronous data streams. This means that you can leverage
The HTTP support of Angular2 leverages operators (flatMap, ...) to link streams together and implement complex processing chains. This means that you can use all concepts of Reactive Programming / RxJS to make an HTTP request part of an asynchronous data stream.
Here a simple sample that allows to execute a request based on the value of a form input (when updates occur):
this.inputControl.valueChanges.debounceTime(500).flatMap(
val => {
// Execute ab
return this.http.get(`http://...?filter=${val}`);
}).subscribe((data) => {
this.places = data;
});
Operators can also allow to implement easily several issues in the context of HTTP:
Ensure to receive the latest when requests are executed in sequence (for example based on user input). Sample of the switchMap operator that cancels the previous in-progress requests when a new one is triggered
this.ctrl.valueChanges.switchMap(
val => {
return this.http.get(`http://...?filter=${val}`);
});
Buffer events and trigger the last one after an amount of time. Sample that waits for an inactivity of 500ms before executing the request based on the latest value of the input:
this.ctrl.valueChanges.debounceTime(500).flatMap(
val => {
return this.http.get(`http://...?filter=${val}`);
});
Retry when requests fail. Sample of retry each 500ms and within 2s
var params = new URLSearchParams();
params.set('placename_startsWith', searchText);
params.set('username', 'XXX');
return this.http.get('http://api.geonames.org/postalCodeSearchJSON',
{ search: params })
.retryWhen(error => error.delay(500))
.timeout(2000, return new Error('delay exceeded'))
.map(res => res.json().postalCodes);
Here are some articles regarding Reactive Programming that could help you: