角度4>
您可以选择手动设置标头,也可以创建一个HTTP拦截器,以便在每次发出请求时自动设置标头。
手动地
设置标题:
http
.post('/api/items/add', body, {
headers: new HttpHeaders().set('Authorization', 'my-auth-token'),
})
.subscribe();
设置标题:
this.http
.post('api/items/add', body, {
headers: new HttpHeaders({
'Authorization': 'my-auth-token',
'x-header': 'x-value'
})
}).subscribe()
局部变量(不可变再次实例化)
let headers = new HttpHeaders().set('header-name', 'header-value');
headers = headers.set('header-name-2', 'header-value-2');
this.http
.post('api/items/add', body, { headers: headers })
.subscribe()
HttpHeaders类是不可变的,因此每个set()返回一个新实例并应用更改。
来自Angular文档。
HTTP拦截器
@ angular / common / http的主要功能是拦截,即声明位于应用程序和后端之间的拦截器的功能。 当您的应用程序发出请求时,拦截器会先对其进行转换,然后再将其发送到服务器,并且拦截器可以在应用程序看到请求之前将响应转换回去。 这对于从身份验证到日志记录的所有操作都是有用的。
来自Angular文档。
确保在整个应用程序中使用@angular/common/http。 这样,您的请求将被拦截器捕获。
步骤1,创建服务:
import * as lskeys from './../localstorage.items';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http';
@Injectable()
export class HeaderInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
if (true) { // e.g. if token exists, otherwise use incomming request.
return next.handle(req.clone({
setHeaders: {
'AuthenticationToken': localStorage.getItem('TOKEN'),
'Tenant': localStorage.getItem('TENANT')
}
}));
}
else {
return next.handle(req);
}
}
}
步骤2,将其添加到您的模块中:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HeaderInterceptor,
multi: true // Add this line when using multiple interceptors.
},
// ...
]
有用的链接:
拦截器无法正常工作。
APP_INITIALIZER无法与拦截器结合使用