0

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.

3
  • 1
    please just have a look at the following resource stackoverflow.com/questions/45286764/…. Commented Jan 4, 2019 at 15:15
  • @KishoreKumar I am using get request Commented Jan 4, 2019 at 15:18
  • 1
    this.httpClient.get(url, {headers}) Commented Jan 4, 2019 at 22:13

1 Answer 1

1

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

1 Comment

Is it possible that I can assign only the token value with a variable "newToken" and then call n my headers ?? eg: var newToken ="frorjakfngfausjflsf" and later headers: [[authorization : bearer + newToken]]

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.