So, today I came across something similar. My situation is a little different, I expanded Http, for which I need Router. However, ErrorHandler also needed Http. Using the method above with Factories, I thought I could just enter Http in the ErrorHandler. I found that when ErrorHandler caused dependency injection in the constructor for Http, the router did not exist (and it did not have any other necessary context).
So, I have an injector to get an instance during a function call, and not in the constructor. That when the injector is really trying to get Http (in a call), it is already created in the appropriate context.
CustomErrorHandler.ts:
import { ErrorHandler, Injector } from '@angular/core'; import { Http } from '@angular/http'; import { environment } from 'environments/environment'; export class CustomErrorHandler extends ErrorHandler { private http: Http; constructor(private injector: Injector) { super();
Relevant parts from CustomHttpService.ts:
@Injectable() export class CustomHttpService extends Http { constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private router: Router, private injector: Injector) { super(backend, defaultOptions); } request(urlOrRequest: string | Request, options?: RequestOptionsArgs): Observable<Response> {
app.module.ts:
import { NgModule, ErrorHandler, Injector } from '@angular/core'; import { Http, RequestOptions, XHRBackend } from '@angular/http'; import { CustomErrorHandler } from 'app/customErrorHandler'; // ... export function customHttpServiceFactory(xhrBackend, requestOptions, router, injector) { return new CustomHttpService(xhrBackend, requestOptions, router, injector); } export function customErrorHandler(injector) { return new CustomErrorHandler(injector); } @NgModule({ declarations: [ ... ], imports: [ ... ], providers: [ { provide: Http, useFactory: customHttpServiceFactory, deps: [XHRBackend, RequestOptions, Router, Injector] }, // { provide: UrlSerializer, useClass: LowercaseUrlSerializer }, { provide: ErrorHandler, useFactory: customErrorHandler, deps: [Injector] }, ... ], bootstrap: [AppComponent] }) export class AppModule {}