chromate chromate - 11 days ago 5
TypeScript Question

Angular 2 - Mix dependency injection in constructor with other arguments

In the following class I'd like to abstract away the http dependency, such that Angular 2 uses the normal dependency injection to inject the http object.

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

class MyCollectionView<T> extends CollectionView {
constructor(private endpoint: string, private http: Http) {
}

// ... implemenation of class ...
}


I'd like to use the class as follows:

class MyClass {
private collection: MyCollectionView<ITestRow>;

constructor() {
this.collection = new MyCollectionView<ITestRow>('/some/endpoint');
}
}


To instantiate in my current implementation I have to write

class MyClass {
private collection: MyCollectionView<ITestRow>;

constructor(private http: Http) {
this.collection = new MyCollectionView<ITestRow>('/some/endpoint', http);
}
}


As far as I know it's not possible to combine ng2 dependency injection and custom arguments in the constructor. I think I need some kind of factory function that takes care of the dependency injection part but so far I have had no luck. Especially since the class uses also generics. Are there any best practices that I can follow here?

Please note that in unit tests it should still be possible to resolve DI with the
MockBackend
instead.

I found this question on stackoverflow, but its most upvoted answer can not be used IMHO because the arguments have to be dynamic.

Answer

Dependency injection (DI) only works for classes created by DI. If you create classes with new Xxx(), there is no DI happening.

If the instance is created by DI then you can't pass your own parameters.
You would need to create providers for these parameters for DI to be able to inject them.

What you're doing is the correct way.