Angular HttpInterceptor不起作用

时间:2017-08-09 10:02:23

标签: angular angular-http-interceptors

我想实现一个HttpInterceptor,但不知何故,它根本没有做任何事情。

实施HttpInterceptor的自定义服务:

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse} from '@angular/common/http';
import {AuthenticationService} from "./authentication.service";
import {Observable} from "rxjs/Observable";

@Injectable()
export class HttpInterceptorService implements HttpInterceptor {

  constructor(private auth: AuthenticationService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log("INTERCEPTED!!");

    const authHeader = this.auth.getAuthorizationHeader();

    const authReq = req.clone({setHeaders: {Authorization: authHeader}});

    return next.handle(authReq)
      .do((event) => {
        if (event instanceof HttpResponse) {
          console.log(event);
        }
      }, (error: HttpErrorResponse) => {
        console.log(error);
      });
  }
}

app.modules.ts中提供:

  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpInterceptorService,
      multi: true,
    },
    AuthenticationService
  ]

不幸的是,似乎什么也没做。我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

好的,我发现了。要执行get()来电,我仍使用Http中的@angular/http代替HttpClient中的@angular/common/http

现在工作正常。