4

I'm trying to set a default timeout of 10 seconds for each HTTP request I do using HttpClient. I've got an interceptor to add some values to the header, and I've read that to set a timeout you have to use the 'timeout' RxJS operator, like this:

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

import { Observable } from 'rxjs/Observable';
import { timeout } from 'rxjs/operators/timeout';

@Injectable()
export class APIInterceptor implements HttpInterceptor {
  constructor() {

  }

  intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    // NOTE: The following 'authToken' and 'user_id' values are obtained through a global service
    const authReq = req.clone({
      headers: new HttpHeaders ({
        'Content-Type':  'application/json',
        'X_TOKEN_AUTH': authToken,
        'X_IDUSER': user_id
      }) 
    });

    const API_TIMEOUT = 10000;

    //console.log('HEADER: ', authReq)

    return next.handle(authReq).timeout(API_TIMEOUT);   // Set a timeout for the requests
  }
}

Before adding the timeout function, everything worked fine, and the headers got injected the auth token and user ID. However, now I get the following error:

next.handle(...).timeout is not a function

Am I doing something wrong? Thanks!

1 Answer 1

5

If you want to use the "patch" style of operators you need to import it from rxjs/add/operator/*:

import 'rxjs/add/operator/timeout';

The 'rxjs/operators/timeout' method is used when using pipe().

Sign up to request clarification or add additional context in comments.

1 Comment

I am using this, but still getting an error. error TS2339: Property 'timeoutWith' does not exist on type 'Observable<HttpEvent<any>>'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.