拦截器未拦截HTTP POST请求(Angular 6)

时间:2018-08-03 08:05:40

标签: angular angular6 angular-http-interceptors

我创建了一个实现httpinterceptor的角度拦截器。对于http GET请求,它工作正常。但是POST请求失败。

我的拦截器代码如下。

import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest,         HttpHeaders,HttpResponse } from '@angular/common/http';

import { Observable } from 'rxjs';

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  constructor() { console.log('enter constructor');
   }

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    console.log('entered interceptor')
    const token = localStorage.getItem('sessiontoken') != null ?     localStorage.getItem('sessiontoken') : 'notoken';
    const authReq = req.clone({ headers:     req.headers.set("Authorization", token) });

    return next.handle(authReq);

  }

}

该模块随提供程序一起添加。

providers: [
{
  provide: HTTP_INTERCEPTORS,
  useValue: { disableClose: true, minWidth: 400, hasBackdrop: true },
  useClass: MyHttpInterceptor,
  multi: true
}
]

在组件中,我导入了httpClient并使用了此。http.post

import { HttpClient } from '@angular/common/http';

1 个答案:

答案 0 :(得分:10)

我找到了答案,我将HttpClientModule导入了所有子组件的模块。应该仅将其导入app.module.ts中。从每个文件中删除所有HttpClientModule后,问题就解决了,成功将标头绑定到每个请求。 (不记得为什么我实际上不必要地导入了它,有些教程复制错误)

谢谢大家的欢呼

相关问题