Default and specific request timeout
Asked Answered
I

4

96

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 service, to my knowledge.

What is the way to approach this in HttpClient service? How to define a default timeout for all outgoing requests, that can be overriden for specific ones?

Ivar answered 29/8, 2017 at 12:15 Comment(3)
@neuhaus its not angularjs it angular , not a duplicateSwindell
you can make use of timeout operator here ?Swindell
@RahulSingh This is the way it was done in Http, and this approach required to specify .timeout(...) for each request, not by default.Ivar
I
191

It appears that without extending HttpClientModule classes, the only expected ways for interceptors to communicate with respective requests are params and headers 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:

import { Inject, Injectable, InjectionToken } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { timeout } from 'rxjs/operators';
    
export const DEFAULT_TIMEOUT = new InjectionToken<number>('defaultTimeout');
    
@Injectable()
export class TimeoutInterceptor implements HttpInterceptor {
  constructor(@Inject(DEFAULT_TIMEOUT) protected defaultTimeout: number) {
  }
    
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const timeoutValue = req.headers.get('timeout') || this.defaultTimeout;
    const timeoutValueNumeric = Number(timeoutValue);

    return next.handle(req).pipe(timeout(timeoutValueNumeric));
  }
}

This can be configured in your app module like:

providers: [
  [{ provide: HTTP_INTERCEPTORS, useClass: TimeoutInterceptor, multi: true }],
  [{ provide: DEFAULT_TIMEOUT, useValue: 30000 }]
],

The request is then done with a custom timeout header

http.get('/your/url/here', { headers: new HttpHeaders({ timeout: `${20000}` }) });

Since headers are supposed to be strings, the 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.

Ivar answered 31/8, 2017 at 16:20 Comment(17)
@Jota.Toledo I don't think observables alone can help here. Once an observable was chained with.timeout(defaultTimeout) operator inside the interceptor, it's impossible to 'cancel' it and chain with .timeout(customTimeout) instead. This is probably possible by subclassing Observable but it will be cumbersome and fragile too. Hope this will be fixed someday in HttpClient itself. AngularJS $http had timeout option and it worked just great.Ivar
Yup, Im aware of that. I tried to implement something with mergeMap and other operators based in a SO answer, but In one of the cases (I think default overriden by larger time) my approach didnt work. I will choose your approach despite the fact that I dont like the use of HttpHeader for comunication with the interceptor, but in the current state of the API I think there is no better approach.Llewellyn
Yes, since there are no other options to interact with interceptor, headers look like the only one, and it's not really bad. At least the semantics is correct, headers are suppose to carry information about a request. Hope this will be fixed in future versions.Ivar
this code doesn't work to increase timeout request to be bigger than 30s. If you set it to 60 seconds, the angular's default 30 seconds will be appliedBasalt
after adding timeout , do we have any additional parameter sent from UI to backend ?Tripartition
@Tripartition I'm not sure if I understood you correctly, but a request itself doesn't differ. A timeout forces a request to be closed after specified amount of time if there was no response from a server.Ivar
@Tripartition Yes, but only if a server allows that.Ivar
@estus I am trying to use this as it appears to solve all my woes, but I am new to the InjectionToken class and am running into the error StaticInjectorError...No provider for InjectionToken defaultTimeout!. I know it's a longshot, but would you have any idea you can share as to why this is happening?Carpal
@Lopsided Means that you didn't register it as a provider, so you can't inject it. See the part with provide: DEFAULT_TIMEOUT ....Ivar
@EstusFlask I just wanted to give you props for your answer AND your nickname. Praise the sun!Veasey
@EstusFlask Why doesn't your default value of 30000 have to be a string? Is typescript automatically converting that in the useValue property?Redpoll
@Redpoll TS doesn't do any magic at runtime besides the behaviour expected from relevant ES specs. Default timeout is a custom service that isn't used anywhere but in this snippet, so it can be any type we need. Here timeout value needs to be converted into a number in order to be used with timeout any way, making it "30000" instead of 30000 would work the same way but require 2 characters more to type.Ivar
2022 is this still valid?Unhair
@Unhair Afaik yes, Angular doesn't provide anything more specific to implement thisIvar
@Basalt is correct : this code does NOT work. Setting the observable timeout does not have any effect on the timeout of the HttpClient. The feature has been requested but not selected for implementation (github.com/angular/angular/issues/34421). The only solution that is valid for now is to go for an asynchronous solution. Trigger the processing, and come back later when it is complete.Mopboard
@Mopboard Can you provide a demo to debug? Httpclient doesn't need to explicitly support timeouts to make it work, this is what the fix was about. I believe Httpclient aborts xhr req when unsubscribed, this is something that can be expected from observable-based implementation unpkg.com/browse/@angular/[email protected]/fesm2022/http.mjs#L2300, and pipe(timeout()) results in complete observable which is unsubscribed. It's been quite a while, I fixed the demo somehow to not break because of incompatible package versions, notice there are 3 test.json reqs, one of them is aborted on timeoutIvar
@Mopboard Thompson's comment referred 30s timeout that came from elsewhere (most likely a webserver), it's not relevant, other answers may address a possible cause, e.g. https://mcmap.net/q/217770/-default-and-specific-request-timeoutIvar
H
30

In complement to the other answers, just beware that if you use the proxy config on the dev machine, the proxy's default timeout is 120 seconds (2 minutes). For longer requests, you'll need to define a higher value in the configuration, or else none of these answers will work. The timeout must be set in milliseconds (it's set to 6 minutes in the example below).

{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false,
    "timeout": 360000
  }
}
Hepplewhite answered 9/9, 2019 at 21:46 Comment(7)
Thanks for adding this, I only realized I was using a proxy when I read this answer!Anthracoid
Thanks for the awesome answer. May I know where that default timeout value is documented? I can't find it either in angular nor webpack documentation.Libratory
Thanks for this wonderful answer i understood this when only i see this onePickerel
Should this be done on the development server ?Turpentine
This does not work on production server. any solution ?Turpentine
how does 360000 become 120 seconds? Is this value in ms as well?Oscular
The property timeout is set in seconds. This number, 360000, is just an arbitrarily high number to avoid ever getting timed-out.Hepplewhite
S
15

Using the new HttpClient you can try some thing like this

@Injectable()
export class AngularInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).timeout(5000).do(event => {}, err => { // timeout of 5000 ms
        if(err instanceof HttpErrorResponse){
            console.log("Error Caught By Interceptor");
            //Observable.throw(err);
        }
    });
  }
}

Adding a timeout to the next.handle(req) which is passed on.

Registering it in AppModule like

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        HttpClientModule
    ],
    providers: [
        [ { provide: HTTP_INTERCEPTORS, useClass: 
              AngularInterceptor, multi: true } ]
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}
Swindell answered 29/8, 2017 at 12:35 Comment(2)
Thanks. However, as mentioned in another answer, it's seems to be impossible to increase timeout for particular request this way.Ivar
@estus yes that is the hard part as of now I don't think there is any direct solutions to it might have a work around. Will see to it. The other answer was not much different. Just added a throw after time outSwindell
L
15

You could create a global interceptor with the base timeout value as follows:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';

@Injectable()
export class AngularInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).timeout(30000, Observable.throw("Request timed out"));
    // 30000 (30s) would be the global default for example
  }
}

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.

Llewellyn answered 29/8, 2017 at 14:1 Comment(1)
@Mopboard this snippet is 7 years old, lolLlewellyn

© 2022 - 2024 — McMap. All rights reserved.