Angular HttpInterceptor 未更改 header
Angular HttpInterceptor not changing header
我写了一个 angular (4.3.6) HttpInterceptor 来添加一些 header 字段,但是如果我在调试器中检查它们,header 不会更新。有什么想法吗?
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('AuthInterceptor at work');
const contentTypeReq = req.clone({
headers: req.headers.set('Content-Type', 'application/json')
});
const token = localStorage.getItem('token');
if (token) {
const authReq = contentTypeReq.clone({
headers: req.headers.set('Authorization', 'Bearer ' + token)
});
return next.handle(authReq);
}
// Pass on the cloned request instead of the original request.
return next.handle(contentTypeReq);
}
}
他们很懒惰。例如 keys
method 看起来像:
keys(): string[] {
this.init(); <== initialize
return Array.from(this.normalizedNames.values());
}
如果您想查看它们,请致电:
req.headers.keys()
如果要检查值,可以使用 get
或 getAll
方法:
req.headers.getAll('Content-Type')
或者您可以从控制台调用 init
方法,然后您将能够在 headers
Map
中看到 headers
此外,当angular adds headers to request it uses forEach方法调用init
方法时。
我写了一个 angular (4.3.6) HttpInterceptor 来添加一些 header 字段,但是如果我在调试器中检查它们,header 不会更新。有什么想法吗?
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('AuthInterceptor at work');
const contentTypeReq = req.clone({
headers: req.headers.set('Content-Type', 'application/json')
});
const token = localStorage.getItem('token');
if (token) {
const authReq = contentTypeReq.clone({
headers: req.headers.set('Authorization', 'Bearer ' + token)
});
return next.handle(authReq);
}
// Pass on the cloned request instead of the original request.
return next.handle(contentTypeReq);
}
}
他们很懒惰。例如 keys
method 看起来像:
keys(): string[] {
this.init(); <== initialize
return Array.from(this.normalizedNames.values());
}
如果您想查看它们,请致电:
req.headers.keys()
如果要检查值,可以使用 get
或 getAll
方法:
req.headers.getAll('Content-Type')
或者您可以从控制台调用 init
方法,然后您将能够在 headers
Map
此外,当angular adds headers to request it uses forEach方法调用init
方法时。