8

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.

enter image description here 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?

1
  • If you want to send auth token why don't you use an http interceptor ? Commented Jun 26, 2019 at 7:01

4 Answers 4

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();
  }
Sign up to request clarification or add additional context in comments.

2 Comments

I have added header to get request as you told. Got this error ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":401,"statusText":"Unauthorized","url"
Then your auth key is wrong. Check your auth key again
1

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();

Comments

1
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);
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.