【问题标题】:Angular HttpInterceptor does not workAngular HttpInterceptor 不起作用
【发布时间】:2017-08-09 18:12:10
【问题描述】:

我想实现一个 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
  ]

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

【问题讨论】:

    标签: angular angular-http-interceptors


    【解决方案1】:

    好的,我发现了。为了执行get() 调用,我仍然使用来自@angular/httpHttp 而不是来自@angular/common/httpHttpClient

    现在可以正常使用了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-02
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      • 2018-05-16
      相关资源
      最近更新 更多