Angular HttpHeaders 不是设置值

Angular HttpHeaders is not setting value

我正在尝试为其中一个获取请求设置 headers。以下是函数:

 getLeads(jwtToken: string): Observable<any>{
    const headers = new HttpHeaders();
    const authroizationToken = 'bearer '.concat(jwtToken);
    console.log(authroizationToken);          ------------------>  prints the token
    headers.append('Authorization', authroizationToken);
    console.log(headers.get('Authorization'));  ---------------------> this prints null
    var result = this.http.get<Leads>(this.getLeadsUrl, {headers});
    return result;
  }

但是 heades.get('Authorization') 由于某种原因为空,我无法弄清楚原因。任何帮助将不胜感激。

对您的代码进行以下更改:

getLeads(jwtToken: string): Observable<any>{
    let httpOptions = {
      headers: new HttpHeaders({ 'Authorization': `bearer ${jwtToken}` })
    };
    return  this.http.get<Leads>(this.getLeadsUrl, httpOptions);
}

您可以使用 HttpHeaders 的 set() 方法:

Which sets or modifies a value for a given header in a clone of the original instance. If the header already exists, it's value is replaced with the given value in the returned object.

一个例子:

let header = new HttpHeaders().set(
  "Authorization",`bearer ${jwtToken}`
);

return this.http.get<Leads>(this.getLeadsUrl,  {headers:header});

实际上 .append returns 新的 headers objects。试试这个它按预期工作。每次附加新的 header.

时,请确保将 header 分配回变量
   getLeads(jwtToken: string) {
    let headers = new HttpHeaders();
    const authroizationToken = 'bearer '.concat(jwtToken);
    console.log(authroizationToken);
    headers = headers.append('Authorization', authroizationToken);
    console.log(headers.get('Authorization'));
  }

这是一个有效的Stackblitz

希望这对您有所帮助:)

问题在以下线程中有答案。

https://whosebug.com/a/45286959/12376898

https://whosebug.com/a/47805759/12376898

总而言之,headers 是不可变的,因此进行任何更改都会创建一个新的 object。除非您将新创建的 object 引用到旧引用,否则只有旧的 object 会保留。

getLeads(jwtToken: string) {
let headers = new HttpHeaders();
headers.append('ANYHEADER','SOMESTRING') // will be lost
headers = headers.append('ANYHEADER','SOMESTRING') //unless you reference it again to the old reference
}