What is the "best" (common) way to make sure that my Angular HTTP request only returns the newest response data. (I am using Angulars HttpClient)
Lets say the user submits a new request before the response of the previous request is returned. My backend needs more time to process the first request so the second request returns before the first one -> the view get's updated and later the first request returns. Now the view gets updated with old data. Thats obviously not what I want.
I found this solution to cancel the request but is that really the only way? Are there any build in functionalities to achive that?
if ( this.subscription ) {
this.subscription.unsubscribe();
}
this.subscription = this.http.get( 'myAPI' )
.subscribe(resp => {
// handle result ...
});
I know there is the switchMap() operator which only returns the latest data but as far as I know you can only use it inside of an observable. In my case I am not observing any input changes. I simply call a function on form submit via (ngSubmit)="doRequest()" directive in HTML-Template.
// get called on submit form
doRequest() {
this.http.get('myAPI')
.subscribe(resp => {
// handle result ...
});
}
Is there a way to use the switchMap operator or do you have any other solutions? Thanks for taking your time :)
PS: Of course in my real project I have an api service class with different functions doing the requests and just returning http response observables. So I subscribe to such an observable in doRequest() function.