19

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.

Community
  • 1
  • 1
dotcs
  • 2,286
  • 1
  • 18
  • 26

2 Answers2

16

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Makes sense, thanks for the confirmation. Since this class will always be constructed manually and not via dependency injection I'll leave it as it is. :) – dotcs Nov 28 '16 at 16:47
0

As far as I know it's not possible to combine ng2 dependency injection and custom arguments in the constructor.

In angular 4 you can do it. See my answer here https://stackoverflow.com/a/46813768/586609

Stanislav Berkov
  • 5,929
  • 2
  • 30
  • 36