Nib*_*aby 2 angular-http-interceptors angular angular6
我创建了一个实现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);
}
}
Run Code Online (Sandbox Code Playgroud)
该模块添加了提供程序.
providers: [
{
provide: HTTP_INTERCEPTORS,
useValue: { disableClose: true, minWidth: 400, hasBackdrop: true },
useClass: MyHttpInterceptor,
multi: true
}
]
Run Code Online (Sandbox Code Playgroud)
在组件中我导入了httpClient并使用了this.http.post
import { HttpClient } from '@angular/common/http';
Run Code Online (Sandbox Code Playgroud)
Nib*_*aby 13
我找到了答案,我将HttpClientModule导入了所有子组件的模块.它应该只在app.module.ts中导入.一旦我从每个文件中删除了所有HttpClientModule,问题就解决了,成功地将标头绑定到每个请求.(不记得为什么我实际上不必要地导入它,一些教程复制错误)
谢谢大家,欢呼
| 归档时间: |
|
| 查看次数: |
3520 次 |
| 最近记录: |