Usually it's desirable to have default timeout (e.g. 30s) that will be applied to all requests and can be overridden for particular longer requests (e.g. 600s).
There's no good way to specify default timeout in Http
, to my knowledge.
What is the way to approach this in HttpClient
?
How to define a default timeout for all outgoing requests, that can be overriden for specific ones?
Using the new HttpClient you can try some thing like this
Adding a timeout to the
next.handle(req)
which is passed on.Registering it in AppModule like
It appears that without extending
HttpClientModule
classes, the only expected ways for interceptors to communicate with respective requests areparams
andheaders
objects.Since timeout value is scalar, it can be safely provided as a custom header to the interceptor, where it can be decided if it's default or specific timeout that should be applied via RxJS
timeout
operator:This can be configured in your app module like:
The request is then done with custom
timeout
headerSince headers are supposed to be strings, timeout value should be converted to a string first.
Here is a demo.
Credits go to @RahulSingh and @Jota.Toledo for suggesting the idea of using interceptors with
timeout
.You could create a global interceptor with the base timeout value as follows:
Afterwards you need to register this injectable in the providers array of you root module.
The tricky part would be to override the default time (increase/decrease) for specific requests. For the moment I dont know how to solve this.