首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular HttpInterceptor不工作

Angular HttpInterceptor不工作
EN

Stack Overflow用户
提问于 2017-08-09 18:02:23
回答 1查看 1.1K关注 0票数 0

我想实现一个HttpInterceptor,但不知何故,它什么也做不了。

实现HttpInterceptor的自定义服务

代码语言:javascript
复制
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中提供

代码语言:javascript
复制
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpInterceptorService,
      multi: true,
    },
    AuthenticationService
  ]

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-09 18:12:10

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

现在它工作得很好。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45587506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档