angular - 无法在 httpclient 中设置自定义标头(ionic 3 app angular 5)
问题描述
我正在尝试使用需要 API 密钥“Auth”的 api,我正在尝试使用以下代码使用 httpHeaders 发送密钥
getTest(){
let data = {'loginusertype':'12','loginuserid':'51','apitype':'1','start':'0','end':'20'};
let headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8','Auth':'593eb2c274d640a8798493bf340e08b6'});
this.http.post('http://www.mymediaxchange.com/api/serviceapi/v1/currentworks',data,{headers:headers})
.subscribe(
(data) => console.log(data),
(error) => console.log(error)
) }
我尝试过的事情
1)使用的拦截器
2)这个问题中的解决方案
Angular HttpClient 不发送标头
3)this.http.post('mymediaxchange.com/api/serviceapi/v1/currentworks',data,{headers: {'Auth': 'YourAuthorizationKey'}})
解决方案
您可以尝试为此使用拦截器服务。它的作用是为应用程序的每个请求添加一个 Authorization 标头。
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with token
const currentUser = JSON.parse(String(localStorage.getItem('currentUser')));
if (currentUser && currentUser.Token) {
request = request.clone({
setHeaders: {
Authorization: `${currentUser.Token}`
}
});
}
return next.handle(request);
}
}
并在您的模块提供程序部分使用它。
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: JwtInterceptor,
multi: true
}
]
推荐阅读
- java - SpEL 语言 - 自动空引用初始化
- kivy - 只旋转图像而不是矩阵
- java - 有没有办法让 gecko.driver 在共享代码中对每个人都可用?
- excel - 使用数据验证和条件格式的逻辑在表中插入第一行
- c - C中嵌套for循环中的条件不起作用
- arrays - 如何在 sting 数组中附加 Json 值?
- python - sklearn.preprocessing.normalize 如何规范化数据,我可以在新数据上复制均值和标准差吗?
- python - 如何以 Python 方式在 MatLab 中解压二进制数据
- django - 如何在 DRF 中为 GET 添加序列化器字段而不是 POST?
- prestashop - PrestaShop / 获取自定义产品字段 - 从购物车