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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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. :)
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.