How to cancel/abort all pending HTTP requests angular 4+.
There is an unsubscribe
method to cancel HTTP Requests but how to cancel all pending requests all at once.
Especially while route change.
There is one thing I did
ngOnDestroy() {
this.subscription.unsubscribe();
}
but how to achieve this globally
Any Ideas?
I'm not convinced of the need for the functionality requested, but you can accomplish this, cancelling all outstanding requests whenever and wherever you wish by wrapping the framework's http service and delegating to it.
However, when we go about implementing this service, a problem quickly becomes apparent. On the one hand, we would like to avoid changing existing code, including third party code, which leverages the stock Angular http client. On the other hand, we would like to avoid implementation inheritance.
To get the best of both worlds we can implement the Angular
Http
service with our wrapper. Existing code will continue to work without changes (provided said code does not do anything stupid like usehttp instanceof Http
).Note that the
interface
andclass
declarations forCancellationAwareHttpClient
are merged. In this way, our class implementsHttp
by virtue of theinterface
declaration'sextends
clause.Now we will provide our service
Note how we override the existing framework provided service. We use a factory to create our instance and do not add any decorators for DI to the wrapper itself in order to avoid a cycle in the injector.
If you don't want to manually unsubscribe all subscriptions, then you can do this:
Then you can use it as decorator in your component
but you still need to store subscriptions as component properties. And when you navigating out of component, AutoUnsubscribe function will occurs.
ngOnDestroy
callback is typically used for any custom cleanup that needs to occur when the instance is destroyed.where do you want to cancel your request?
maybe if you want cancel your requests on browser close there is creative idea here
You can create an interceptor to apply
takeUntil
operator to every request. Then on route change you will emit event that will cancel all pending requests.Helper service.
Hook on route changes somewhere in your app (e.g. onInit in appComponent).
You can make a custom Http Service (using HttpClient) which maintains a list of pending requests. Whenever you fire a http us this custom service instead of Http/HttpClient,now push the subscriptions to a list and on return of the response pop that subscription out. Using this you will have all the incomplete subscriptions in a list.
Now in the same custom service Inject router in the constructor and subscribe on it to get the route change events. Now whenever this observable emits, all you need to do is to unsubscribe all the subscriptions present in the list and pop all the elements from it.
If you need code snippet, do mention in comment.