拦截器不拦截 http POST 请求 (Angular 6)
Interceptor not intercepting http POST requests (Angular 6)
我创建了一个实现 httpinterceptor 的 angular 拦截器。它适用于 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,问题就解决了,成功地将 headers 绑定到每个请求。 (不记得为什么我实际上不必要地导入它,一些教程复制错误)
谢谢大家,干杯
我创建了一个实现 httpinterceptor 的 angular 拦截器。它适用于 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,问题就解决了,成功地将 headers 绑定到每个请求。 (不记得为什么我实际上不必要地导入它,一些教程复制错误)
谢谢大家,干杯