【发布时间】:2019-01-30 01:12:46
【问题描述】:
谁能告诉我这是否是在 Angular 6 中向 http 请求添加标头的正确方法?
当我通过 SwaggerUI 拨打电话时,我可以看到标题应该是:
url -X GET --header 'Accept: application/json' --header 'zumo-api-version: 2.0.0' 'https://myurl/tables/stuff'
所以我添加了以下内容:
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('HttpHeader1', 'Accept:application/json');
headers = headers.append('HttpHeader2', 'zumo-api-version:2.0.0');
然后调用:
getStuff(){
return this.http.get('https://myurl/tables/stuff', {headers})
}
没有失败但没有返回,我知道应该有。
谢谢
更新
刚刚注意到我调用的 url 实际上是 https 而不是 http,这有什么不同吗?
getStuff(){
return this.https.get('https://myurl/tables/stuff', {headers})
}
【问题讨论】:
-
你得到
HttpHeader1的地方实际上应该是标题名称,即Accept,你得到Accept:application/json的地方应该是值,即application/json,所以你其实想要的是headers.append('Accept', 'application/json'); -
确保在 HTTP 调用中也调用
subscribe。 Observables 是惰性的,所以它只会在订阅了某些东西后才进行 HTTP 调用
标签: angular http visual-studio-code http-headers