1

So basically I need to add custom auth header to all requests referred to API. In constructor I want to add this header and then in the class methods just use this.http

import { Injectable } from '@angular/core';

import { Config, Events } from 'ionic-angular';

import { Http } from '@angular/http';


@Injectable()

export class APIRequest {

    constructor (
        private http: Http,
        private config: Config,
    ) { 
        this.http.headers.append('My-Custom-Header','MyCustomHeaderValue');
    }
}
user1692333
  • 2,461
  • 5
  • 32
  • 64
  • Possible duplicate of [Angular2 - set headers for every request](http://stackoverflow.com/questions/34464108/angular2-set-headers-for-every-request) – Sabbir Rahman Dec 13 '16 at 07:37
  • @SabbirRahman no, i dont want to set header in each method. I need to set it once in constructor. – user1692333 Dec 13 '16 at 07:39
  • You can create anther service and wrap HTTP there. So there are post, get, .... with your custom header. – Artin Falahi Dec 13 '16 at 08:04

1 Answers1

2

I use common fuction this way for headers

let method = 'POST';

let requestOptions: RequestOptions = new RequestOptions({
headers: this.jsonHeaders(),
method: method
});

jsonHeaders() // Function

public jsonHeaders(): Headers {
let headers: Headers = new Headers();
headers.append('Content-Type', 'application/json; charset=utf-8');
headers.append("Cache-Control", "no-cache");
headers.append("Cache-Control", "no-store");
headers.append("If-Modified-Since", "Mon, 26 Jul 1997 05:00:00 GMT");

if(this.token) {
headers.append('Authorization', 'Bearer ' + this.token);
}

return headers;
}

HTTP Request

let url = '/login'
this.http.request(url, requestOptions)
mayur
  • 3,558
  • 23
  • 37