Direct injection between components
How can inject a B component directly into A component to use its methods without going through the shared module?
Eg:
import { Component } from 'nest.js';
@Component()
export class BComponent {
public bMethod() {
return "foo";
}
}
import { Component } from 'nest.js';
import { BComponent } from '../helper/b.component';
@Component()
export class AComponent {
private aMethod() {
console.log(Bcomponent.bMethod());
}
}
The output: Property 'bMethod' does not exist on type 'typeof Bcomponent'.
Hi @cdiaz,
The thing is your BComponent does not expose its bMethod() has static and that's why you've got an error. So you have 2 choices in the implementation: - expose bMethod() as static - create an instance of your BComponent in aMethod() or in AComponent field (and in this case @Component() decorator is not necessary)
Nethertheless BComponent is a Helper so you can manage it with:
- the dependency injection offered by the framework (@Component() decorator) and inject it in AComponent constructor
- import it like you want but it will never be covered by the framework in term of injection
In my opinion this is not an issue but probably a misunderstood of the framework philosophy or typescript usage...
@ThomRick Thanks.. For now I decided to inject it into the constructor, and obviously the use of the @component decorator is not necessary.
According to the framework philosophy "Almost everything is a component – Service, Repository, Provider etc. and they might be injected to controllers or to another component by constructor"
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.