I am trying to use switchMap to cancel any previous http calls in Angular2. The code is basically
var run = ():Observable => {
var url = \'
I think when you use the switchMap
operator, you can only cancel requests in the current data flow. I mean the events that occur on the same observable chain...
If you call your pollTasks
method several times, you won't be able to the cancel previous requests because they won't be in the same data flow... You create an observable chain each time you call the method.
I don't know how you trigger the execution of your requests.
If you want to execute your request each 500ms, you could try this:
pollTasks() {
return Observable.interval(500)
.switchMap(() => run())
.map(res => res.json());
}
In this case, if there are in-progress request after 500ms, they will be canceled to execute the new one
With the approach, you just need to call once the pollTasks
method.
You can also trigger the asynchronous processing chain based on user events. For example, when characters are filled in inputs:
var control = new Control();
// The control is attached to an input using the ngFormControl directive
control.valueChanges.switchMap(() => run())
.map(res => res.json())
.subscribe(...);
There is a proposal to link / initiate more easily processing chain on DOM events (fromEvent
)
See this link: