簡體   English   中英

攔截器不攔截http POST請求(Angular 6)

[英]Interceptor not intercepting http POST requests (Angular 6)

我創建了一個實現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並使用了this.http.post

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

我找到了答案,我將HttpClientModule導入了所有子組件的模塊。 它應該只在app.module.ts中導入。 一旦我從每個文件中刪除了所有HttpClientModule,問題就解決了,成功地將標頭綁定到每個請求。 (不記得為什么我實際上不必要地導入它,一些教程復制錯誤)

謝謝大家,歡呼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM