R3Tech
R3Tech

Reputation: 801

Angular 2 Dependency injection outside from constructor for instantiation

Every tutorial about DI in Angular 2 is to set the dependencies into the constructor. But what if I want to create an instance of the class and the class have some dependencies to other classes.

I have class A and B. Class B should be inject into A. But A is different every time and should be able to create a instance of it.

If I set up the DI in the constructor from A, how to call new A() ?

I tried to add B as private variable to A with the @Inject(B) decoration.

class A {
  @Inject(B) b: B;
}

Upvotes: 2

Views: 3679

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658067

Angular dependency injection only supports constructor injection.

You can inject an injector

constructor(private injector:Injector) {}

foo() {
  var x = injector.get(B);
  var a = new A(b);
}

This might also help in your case where DI injects a factory function that returns a new instance every time it's called. Create new instance of class that has dependencies, not understanding factory provider

You can also set up new injectors, also one that include parent injectors for finding providers. See also Getting dependency from Injector manually inside a directive

Upvotes: 1

Related Questions