How to add header to a post request in angular 2?

utkarshver picture utkarshver · Jun 1, 2017 · Viewed 15.2k times · Source
//In services.ts

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/Rx';
@Injectable()
export class DataService {

constructor(private http: Http) {   }
fetch(){
   return this.http.get('json-object-link').map(
      (res) => res.json()
    )
       }

 }

//In component

 ngOnInit() {

 this.dataService.fetch()
    .subscribe(
      (data) => this.ninjas = data
    );
}

I want to add the following header to this request:
"headers":
{
"content-type": "application/json",
"access_token": "abcd"
}

Answer

Praneeth Reddy picture Praneeth Reddy · Jun 1, 2017
@Injectable()
export class UserService {
    constructor (private http:HttpClient) {}

    getUserByName(username: string) {
        let url="http://localhost:8088/rest/user/userName";
        let header=new Headers({'Content-Type': 'application/json', 'Authorization': 
            'Bearer '+localStorage.getItem("access_token")});
        return this.http.post(url, username, {headers: header});
    }
}