简体   繁体   English

如何在 angular 中将自定义标头添加到 httpRequest

[英]how to add custom headers to httpRequest in angular

I am trying make an http get() request by passing some values in headers , Now i am replacing the headers like this:我正在尝试通过在headers中传递一些values来发出http get()请求,现在我正在像这样替换headers

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {ICustomer} from 'src/app/models/app-models';

@Injectable({
  providedIn: 'root'
})
export class MyService {
private baseUrl = '....api url....';
public authKey = '....auth_key......';

  constructor(private http: HttpClient) { }

  public async AllCustomers(): Promise<ICustomer[]> {
   const apiUrl = `${this.baseUrl}/customers`;

   return this.http.get<ICustomer[]>(apiUrl ,
    {headers: new HttpHeaders({Authorization: this.authKey})}).toPromise();<=====
  }

}

When i replace the headers like this:当我像这样替换标题时:

headers: new HttpHeaders({Authorization: this.authKey})

The default headers values(i,e Content-Type: application/json) will be replaced by the above headers.默认标头值(即 Content-Type:application/json)将被上述标头替换。

在此处输入图像描述 Instead of replacing the headers how can i add custom headers , I tried like this:我没有替换标题如何添加custom headers ,而是这样尝试:

  public async AllCustomers(): Promise<ICustomer[]> {
    const apiUrl = `${this.baseUrl}/courses`;
    const headers = new HttpHeaders();
    headers.append('Authorization', this.authKey);
    headers.append('x-Flatten', 'true');
    headers.append('Content-Type', 'application/json');

    return this.http.get<ICustomer[]>(apiUrl).toPromise();
  }

What's wrong with my approach, I am new to angular , Any help?我的方法有什么问题,我是angular的新手,有什么帮助吗?

You should add header to your get request like this.您应该像这样将标头添加到您的获取请求中。 Also since HttpHeaders is immutable object you have to reassign header object此外,由于 HttpHeaders 是不可变对象,因此您必须重新分配标头对象

  public async AllCustomers(): Promise<ICourses[]> {
    const apiUrl = `${this.baseUrl}/courses`;
    let headers = new HttpHeaders();
    headers = headers.append('Authorization', this.authKey);
    headers = headers.append('x-Flatten', 'true');
    headers = headers.append('Content-Type', 'application/json');

    return this.http.get<ICourses[]>(apiUrl, {headers}).toPromise();
  }

I think you forgot to add headers object in request我想你忘了在请求中添加 headers 对象

From

return this.http.get<ICourses[]>(apiUrl).toPromise();

To

return this.http.get<ICourses[]>(apiUrl, { headers }).toPromise();
import { HttpHeaders } from '@angular/common/http';
import { HttpClient } from '@angular/common/http';


constructor(private _http: HttpClient) { 

}


public getHeaders(): HttpHeaders {
  const headers = new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': `Bearer ${this._auth.token}`
  });
  return headers;
}


public getData() {
  const url     = `https://stackoverflow.com/api/test`;
  const body    = { };
  const options = { headers: this.getHeaders() };
  return this._http.post<any>(url, body, options);
}

For Angular 15, below code works (thanks to George C.)对于 Angular 15,以下代码有效(感谢 George C。)

let headers = new HttpHeaders({'customHeader': 'customHeaderValue'});

return this.http.post<any>(BaseUrl + 'api/endpoint', formData, { headers: headers, observe: 'response' })

However below code sample only does lazy updates.但是下面的代码示例只进行延迟更新。

let headers = new HttpHeaders();
headers = headers.set('customHeader': 'customHeaderValue');
return this.http.post<any>(BaseUrl + 'api/endpoint', formData, { headers: headers, observe: 'response' })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM