Angular 4 Http 拦截器:next.handle(...).do 不是函数

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

我创建这个 HTTPInterceptor 是为了能够更好地处理 http 错误,在我执行 git pull 和 运行 npm install 之前它运行良好。

这是我的代码:

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);
                    }
                }
            });
    }
}

这是我得到的错误:

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 (

最近是否更改了影响我的代码的内容?我现在可以做什么来 "catch" 我的拦截器上的 http 响应?

抛出此错误是因为您缺少 do 运算符。下面导入并使用 do 运算符修补可观察对象。

import 'rxjs/add/operator/do';

RxJs 默认情况下并未捆绑所有运算符函数以减小库大小。您需要单独导入要使用的运算符。

我最终更改了运算符:

next.handle(req).do

为此:

next.handle(req).subscribe

好像是:

  1. 默认不再加载 rxjs 的运算符

  2. 由于 Angular 已经在 HTTP 调用上实现了 observables,订阅是正确的选择

你必须使用导入。

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

rxjs 6 / angular 6 需要管道

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