httpheaders没有在Angular 9的GET请求中设置?

huangapple go评论65阅读模式
英文:

httpheaders not set in angular 9 get?

问题

在Angular 9中:

const headers = new HttpHeaders()
    .set('Content-Type', 'application/json; charset=utf-8')
    .set('Authorization', this.getToken());   
return this.httpClient.get(url, { headers: headers }).pipe(catchError(this.handleError));

无法连接到HttpHeaders。为什么在GET、POST、PUT、DELETE调用中未附加头部?

英文:

In Angular 9

const headers = new HttpHeaders()
.set('Content-Type', 'application/json; charset=utf-8')
.set('Authorization', this.getToken());   
return this.httpClient.get(url,{headers:headers}).pipe(catchError(this.handleError));

can't connect httpheaders. headers not attached with get post put delete call why ?

答案1

得分: 2

以下是正确的语法:

const httpOptions = new HttpHeaders({
  'Content-Type': 'application/json',
  'Authorization': this.getToken()
});
this.httpClient.get(url, httpOptions).pipe(catchError(this.handleError));
英文:

Here is the correct syntax :

const httpOptions = new HttpHeaders({
  'Content-Type': 'application/json',
  'Authorization': this.getToken()
});
this.httpClient.get(url, httpOptions).pipe(catchError(this.handleError));

答案2

得分: -1

你可以尝试这样做:

let headers = new HttpHeaders()
headers = headers.set('Content-Type', 'application/json; charset=utf-8')
headers = headers.set('Authorization', this.getToken())
return this.httpClient.get(url, { headers: headers }).pipe(catchError(this.handleError))

由于httpheader和httpparams在性质上是不可变的,所以将其分配给返回的对象应该可以工作。

英文:

You can try this:-

let headers = new HttpHeaders()
headers=headers.set('Content-Type', 'application/json; charset=utf-8')
headers=headers.set('Authorization', this.getToken());   
return this.httpClient.get(url,{headers:headers}).pipe(catchError(this.handleError));

Since httpheader and httpparams are kinda immutable in nature so assiging it to the returned object should work.

huangapple
  • 本文由 发表于 2020年1月6日 02:40:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/59603049.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定