I followed this post (http://www.adonespitogo.com/articles/angular-2-extending-http-provider/) to extends Http class and added an static method which returns a singleton of Http.
./services/http.service.ts
import { Injectable, ReflectiveInjector } from '@angular/core';
import {
BaseResponseOptions,
BaseRequestOptions,
BrowserXhr,
ConnectionBackend,
CookieXSRFStrategy,
Headers,
Http as HttpParent,
Request,
RequestOptions,
RequestOptionsArgs,
Response,
ResponseOptions,
XHRBackend,
XSRFStrategy
} from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class CustomHttp extends HttpParent {
public static getInstance() {
if (!(this._instance instanceof CustomHttp)) {
this._instance = ReflectiveInjector.resolveAndCreate([
CustomHttp, BrowserXhr, XHRBackend,
{ provide: ConnectionBackend, useClass: XHRBackend },
{ provide: ResponseOptions, useClass: BaseResponseOptions },
{ provide: XSRFStrategy, useFactory: () => {
return new CookieXSRFStrategy();
}
},
{ provide: RequestOptions, useClass: BaseRequestOptions }
]).get(CustomHttp);
}
return this._instance;
}
private static _instance: CustomHttp;
}
./app.module.ts
import { NgModule } from '@angular/core';
import { HttpModule, RequestOptions, XHRBackend } from '@angular/http';
import { CustomHttp } from './services/http.service';
@NgModule({
bootstrap: [
AppComponent
],
declarations: [
AppComponent
],
imports: [
HttpModule
],
providers: [
{
provide: CustomHttp,
useFactory: (backend: XHRBackend, options: RequestOptions) => {
return new CustomHttp(backend, options);
},
deps: [XHRBackend, RequestOptions]
};
]
})
export class AppModule {}
./services/validation.service.ts
import CustomHttp from './http.service';
export class ValidationService {
static public doSomething() {
CustomHttp.getInstance().get('some/api/').subscribe(
(response) => {
console.log(response);
})
}
}
I hope it works for you.