Search code examples
javascriptangularhttptimeout

Is there an HTTP Connection Timeout in client-side JS/Angular?


I'm using Angular's HttpClient to make HTTP requests and I'd like to specify a timeout for them.

I know I can use HTTPInterceptors and add a timeout to RxJS operators, however, these apply to the whole request which I don't want to abort if data transfer is in progress, only if the browser is hanging while trying to connect.

The kind of timeout I need is available in Node.js for example which is well explained here:

Let's say you called socket.setTimeout(300) to set the timeout as 300 ms, and it took 100 ms for DNS lookup, 100 ms for making a connection with a remote server, 200 ms for the remote server to send response headers, 50 ms for transferring the first half of the response body and another 50 ms for the rest. While the entire request & response took more than 500 ms, timeout event is not emitted at all.

Is it possible to have a timeout like this in an Angular app?


Solution

  • I looked at the source code for the HttpClient. The code that actually deals with the underlying XMLHttpRequest is the class HttpXhrBackend, in source file named xhr.ts

    Unfortunately, HttpXhrBackend just uses the default settings of XMLHttpRequest, and does not provide a way to set the XMLHttpRequest's timeout value.

    I have seen suggestions for using RxJS operators to shorten the effective timeout, but that's a bit of a hack, and doesn't really do what you are asking for.

    So, technically, the answer to your question is "No", not with the stock Angular HttpClient, but I suppose that you could create your own implementation of HttpBackend and attempt to inject that.

    P.S. This article shows how to provide a custom HttpBackend implementation.