Multitut
Multitut

Reputation: 2169

Angular 4 Http Interceptor: next.handle(...).do is not a function

I created this HTTPInterceptor to be able to better handle http errors, it was working well before I did a git pull and ran npm install.

This is my code:

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from "rxjs";
import {ToasterService} from "angular2-toaster";

@Injectable()
export class GobaeInterceptor implements HttpInterceptor {
    constructor(private toasterService: ToasterService){
    }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req)
            .do(event => {
                if (event instanceof HttpResponse) {
                    let response = event.body;
                    if(response.Error){
                        this.toasterService.pop('error', 'Error '+response.Code, response.Message);
                    }
                }
            });
    }
}

And this is the error I get:

TypeError: next.handle(...).do is not a function at GobaeInterceptor.webpackJsonp.../../../../../src/app/services/gobae.interceptor.ts.GobaeInterceptor.intercept (gobae.interceptor.ts:12) at HttpInterceptorHandler.webpackJsonp.../../../common/@angular/common/http.es5.js.HttpInterceptorHandler.handle (

Did something that can affect my code changed lately? what can I do now to "catch" the http response on my interceptor?

Upvotes: 30

Views: 26216

Answers (4)

Shawn Palmer
Shawn Palmer

Reputation: 351

rxjs 6 / angular 6 will need the pipe

return next.handle(req).pipe(
  tap(event => {
    if (event instanceof HttpResponse) {
      ...
    }
  })
);

Upvotes: 26

Multitut
Multitut

Reputation: 2169

I ended up changing the operator from this:

next.handle(req).do

To this:

next.handle(req).subscribe

It seems that:

  1. Operators from rxjs are not loaded by default anymore

  2. Since Angular has implemented observables on HTTP calls, subscribe is the right one to go

Upvotes: -1

Hebert Godoy
Hebert Godoy

Reputation: 106

You have to use import.

import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/Observable';
import 'rxjs/add/observable/throw';

Upvotes: 8

user8510992
user8510992

Reputation: 546

This error is thrown because you are missing the do operator. The below import with patch the observable object with the do operator.

import 'rxjs/add/operator/do';

RxJs does not come bundled with all the operator functions by default to reduce the library size. You are required to import the operators you would like to use individually.

Upvotes: 53

Related Questions