Search code examples
angular7angular-httpclient

using headers in HTTP client


I am trying to develop a dashboard in angular 7. I wanted to access an URL and get the JSON response in my dashboard. the problem is that my code works fine with an open source URL. but there are few end points, which have authorization request. Aim is to add the headers like the JWT token, authorization to my service and display the data in my dashboard.

I found few resources on the internet which are confusing.

Below is my code I tried in my service.ts

import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(private http: HttpClient) { }

  getlocations() {
    return this.http.get('https://jsonplaceholder.typicode.com/users')
  }
}

Any lead on how to add the header and access them would be really helpful.


Solution

  • The simplest way is to modify a specific request by adding HttpHeaders with the authorization parameter. Here's an example:

    getlocations() {
        return this.http.get(
            'https://jsonplaceholder.typicode.com/users', 
            { headers: new HttpHeaders({'Authorization': 'Bearer ' + token}) }
        );
    }