Does anyone know how to add or create a custom HTTP header using Angular 2? how to inject the http depency and how to use the header as we used in jquery
$.ajax({
url: 'foo/bar',
headers: { 'x-my-custom-header': 'some value' }
});
There are several steps to use the HTTP support of Angular2:
Specify the HTTP module in the SystemJS configuration:
System.config({
(...)
map: {
app: "./src",
'@angular': 'https://npmcdn.com/@angular',
'rxjs': 'https://npmcdn.com/[email protected]'
},
packages: {
app: {
main: './main.ts',
defaultExtension: 'js'
},
'@angular/core': {
main: 'core.umd.js',
defaultExtension: 'js'
},
(...)
'@angular/http': {
main: 'http.umd.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
}
}
});
Set the HTTP_PROVIDERS providers when bootstrapping your application:
bootstrap(AppComponent, [ HTTP_PROVIDERS ]);
Inject an instance of the Http class where you want to execute an HTTP request:
import {Http} from '@angular/http';
@Component({
(...)
})
// It can also be @Injectable() in the case of a service
export class SomeComponent {
constructor(private http:Http) {
}
}
Use the Http instance to execute the request:
import {Http, Headers} from '@angular/http';
@Component({
(...)
})
// It can also be @Injectable() in the case of a service
export class SomeComponent {
(...)
executeRequest() {
let headers = new Headers();
headers.append('x-my-custom-header', 'some value');
this.http.get('foo/bar', { headers });
}
Subscribe on the request response to get the response
executeRequest() {
let headers = new Headers();
headers.append('x-my-custom-header', 'some value');
this.http.get('foo/bar', { headers }).map(res => res.json())
.subscribe((data) => {
this.data = data;
});
}
Don't forget this step since observables are lazy. So without subscribing on them, requests won't be executed
I will suggest you wrap the Http service in your own service that defines your REST endpoints like this:
import { Injectable, } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Headers, Http, Response, RequestOptionsArgs } from '@angular/http';
@Injectable()
export class RestService {
constructor(private http: Http) {}
get<T>(url: string): Observable<T> {
var options = {} as RequestOptionsArgs;
options.headers = this.prepareRequestHeaders();
return this.http.get(url, options)
.map(this.extractData)
.catch(this.handleError);
}
post<T>(url: string, data: any): Observable<T> {
var options = {} as RequestOptionsArgs;
options.headers = this.prepareRequestHeaders();
return this.http.post(url, data, options)
.map(this.extractData)
.catch(this.handleError);
}
put<T>(url: string, data: any): Observable<T> {
var options = {} as RequestOptionsArgs;
options.headers = this.prepareRequestHeaders();
return this.http.put(url, data, options)
.map(this.extractData)
.catch(this.handleError);
}
patch<T>(url: string, data: any): Observable<T> {
var options = {} as RequestOptionsArgs;
options.headers = this.prepareRequestHeaders();
return this.http.patch(url, data, options)
.map(this.extractData)
.catch(this.handleError);
}
delete<T>(url: string): Observable<T> {
var options = {} as RequestOptionsArgs;
options.headers = this.prepareRequestHeaders();
return this.http.delete(url, options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData<T>(response: Response) {
var resp: T;
try {
resp = response.json() as T;
} catch (error) {
}
return resp;
}
private prepareRequestHeaders() {
var headers = new Headers();
headers.append('x-my-custom-header', 'some value');
headers.append('Content-Type', 'application/json');
// etc
return headers;
}
private handleResponse<T>(response: any): T[] {
var resp: T[];
try {
resp = response.json().data as T[];
} catch (error) {
}
return resp;
}
private handleError(error: any): Promise<any> {
return Promise.reject(error.message || error);
}
}
or if you prefer promise:
import { Injectable, } from '@angular/core';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Headers, Http, Response, RequestOptionsArgs } from '@angular/http';
@Injectable()
export class RestService {
constructor(private http: Http) {}
get<T>(url: string): Promise<T> {
var options = {} as RequestOptionsArgs;
options.headers = this.prepareRequestHeaders();
return this.http.get(url, options)
.map(this.extractData)
.catch(this.handleError).toPromise();
}
post<T>(url: string, data: any):Promise<T> {
var options = {} as RequestOptionsArgs;
options.headers = this.prepareRequestHeaders();
return this.http.post(url, data, options)
.map(this.extractData)
.catch(this.handleError).toPromise();
}
put<T>(url: string, data: any):Promise<T> {
var options = {} as RequestOptionsArgs;
options.headers = this.prepareRequestHeaders();
return this.http.put(url, data, options)
.map(this.extractData)
.catch(this.handleError).toPromise();
}
patch<T>(url: string, data: any):Promise<T> {
var options = {} as RequestOptionsArgs;
options.headers = this.prepareRequestHeaders();
return this.http.patch(url, data, options)
.map(this.extractData)
.catch(this.handleError).toPromise();
}
delete<T>(url: string):Promise<T> {
var options = {} as RequestOptionsArgs;
options.headers = this.prepareRequestHeaders();
return this.http.delete(url, options)
.map(this.extractData)
.catch(this.handleError).toPromise();
}
private extractData<T>(response: Response) {
var resp: T;
try {
resp = response.json() as T;
} catch (error) {
}
return resp;
}
private prepareRequestHeaders() {
var headers = new Headers();
headers.append('x-my-custom-header', 'some value');
headers.append('Content-Type', 'application/json');
// etc
return headers;
}
private handleResponse<T>(response: any): T[] {
var resp: T[];
try {
resp = response.json().data as T[];
} catch (error) {
}
return resp;
}
private handleError(error: any): Promise<any> {
return Promise.reject(error.message || error);
}
}