N
N
nuclear_kote2016-10-21 00:03:36
Angular
nuclear_kote, 2016-10-21 00:03:36

How to override class constructor in Angular 2?

There is class A:

export class A {
     constructor(protected http: Http) {
     }
}

There is class B:
export class B extends A {
     constructor(protected http: BetterHttp) {
        console.log(http);
     }
}

There is some reimplementation of BetterHttp:
@Injectable()
export class BetterHttp extends Http {

    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
        super(backend, defaultOptions);
    }
.....
}

module:
@NgModule({
   providers: [
        {
            provide: BetterHttp ,
            useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) => {
               return new SecurityHttp(xhrBackend, requestOptions, authService, router);
            },
            deps: [XHRBackend, RequestOptions]
        }
    ]
})
export class CModule {
}

the problem is that B still continues to inject Http instead of BetterHttp, but if I make a constructor with BetterHttp in some component not derived from anything, then everything is fine to be injected

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan Lopatin, 2016-10-21
@lorus

@NgModule({
   providers: [
        {
            provide: BetterHttp ,
            useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) => {
               return new SecurityHttp(xhrBackend, requestOptions, authService, router);
            },
            deps: [XHRBackend, RequestOptions]
        },
        {
            provide: Http,
            useExisting: BetterHttp,
        }
    ]
})
export class CModule {
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question