admin管理员组

文章数量:1202351

I am trying make an http get() request by passing some values in headers, Now i am replacing the headers like this:

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.

Instead of replacing the headers how can i add custom headers, I tried like this:

  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?

I am trying make an http get() request by passing some values in headers, Now i am replacing the headers like this:

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.

Instead of replacing the headers how can i add custom headers, I tried like this:

  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?

Share Improve this question edited Oct 11, 2019 at 6:17 Tony 20.1k6 gold badges41 silver badges62 bronze badges asked Jun 26, 2019 at 6:45 SGRSGR 2012 gold badges5 silver badges12 bronze badges 1
  • If you want to send auth token why don't you use an http interceptor ? – CruelEngine Commented Jun 26, 2019 at 7:01
Add a comment  | 

4 Answers 4

Reset to default 15

You should add header to your get request like this. Also since HttpHeaders is immutable object you have to reassign header object

  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

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.)

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' })

本文标签: javascripthow to add custom headers to httpRequest in angularStack Overflow