Search code examples
angularrxjsangular-http-interceptors

Angular 4: Using HTTP interceptor + RxJS timeout operator error


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!


Solution

  • 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().