我创建了一个实现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, …Run Code Online (Sandbox Code Playgroud)