nest icon indicating copy to clipboard operation
nest copied to clipboard

Direct injection between components

Open cdiaz opened this issue 9 years ago • 3 comments

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'.

cdiaz avatar Apr 13 '17 17:04 cdiaz

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 avatar Apr 13 '17 20:04 thomrick

@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"

cdiaz avatar Apr 14 '17 01:04 cdiaz

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.

lock[bot] avatar Sep 25 '19 13:09 lock[bot]