将Angular4应用迁移到Angular6并注意到,没有应用标头:
let headers = new HttpHeaders();
headers.set('email', this.email); // or headers.apply
稍后-headers.keys() //=> []
但是如果在每个set()
上都进行过覆盖,那么它会起作用:
let headers = new HttpHeaders();
headers = headers.set('email', this.seedrsEmail);
由于@angular/common/http
中的标头是不可变的,我应该如何在Interceptor中附加新的标头?
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
req.headers.append('user_token', '1234') // overwrites headers
答案 0 :(得分:0)
我发现的唯一方法是分别添加每个标头。请随时提出一种更好的方法:
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
let newHeaders: HttpHeaders = req.headers;
newHeaders = newHeaders.set('Content-Type', 'application/json')
newHeaders = newHeaders.set('user_token', '6547')
newHeaders = newHeaders.set('Access-Control-Allow-Origin', '*')
newHeaders = newHeaders.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
let newReq = req.clone({headers: newHeaders});
return next.handle(newReq);