如何在Angular2中设置HTTP标头?

编程入门 行业动态 更新时间:2024-10-08 22:51:13
本文介绍了如何在Angular2中设置HTTP标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以基本上我需要为所有引用API的请求添加自定义auth标头。在构造函数中我想添加这个头,然后在类方法中使用 this.http

So basically I need to add custom auth header to all requests referred to API. In constructor I want to add this header and then in the class methods just use this.http

import { Injectable } from '@angular/core'; import { Config, Events } from 'ionic-angular'; import { Http } from '@angular/http'; @Injectable() export class APIRequest { constructor ( private http: Http, private config: Config, ) { this.http.headers.append('My-Custom-Header','MyCustomHeaderValue'); } }

推荐答案

我以这种方式为标题使用常用函数

I use common fuction this way for headers

let method = 'POST'; let requestOptions: RequestOptions = new RequestOptions({ headers: this.jsonHeaders(), method: method });

jsonHeaders() //功能

public jsonHeaders(): Headers { let headers: Headers = new Headers(); headers.append('Content-Type', 'application/json; charset=utf-8'); headers.append("Cache-Control", "no-cache"); headers.append("Cache-Control", "no-store"); headers.append("If-Modified-Since", "Mon, 26 Jul 1997 05:00:00 GMT"); if(this.token) { headers.append('Authorization', 'Bearer ' + this.token); } return headers; }

HTTP请求

let url = '/login' this.http.request(url, requestOptions)

更多推荐

如何在Angular2中设置HTTP标头?

本文发布于:2023-11-23 00:50:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619519.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   HTTP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!