1
votes

I have a fairly large Angular2 application with smart and dumb components, where all the smart components are hooked into a messaging bus:

class SomeSmartComponent {
  constructor(private messageBuss: MessageBuss) {}
}

This is very repetitive and I would prefer to have:

class SomeSmartComponent extends SmartComponent {
  constructor()
}

Ie. moving the common dependency into a parent class. I've tried the following:

class SmartComponent {
  protected messageBuss: MessageBuss

  constructor() {
    let injector: Injector = Injector.resolveAndCreate([MessageBuss])
    this.messageBuss = injector.get(MessageBuss)
  }
}

The problem is that creates a new Injector and a new MessageBuss, where I need the same MessageBuss that is created by the root injector and injected into the service layer.

In other words I need to get access to the singleton MessageBuss created by the root injector without having it set in a constructor. Any help would be much appreciated.

1
Assuming the Injector thing works, it looks even better using DI directly (injecting in the constructor) as we supposed to do with ng2.Eric Martinez
The point of doing this is to avoid the repetition of having 50+ components that all explicitly inject the same dependency in their constructors and all have common functionality around that dependency. I looked at injecting the Injector but that results in the same amount of repetition.Matthew de Nobrega

1 Answers

0
votes

You would at least need to inject the Injector

class SmartComponent {
  protected messageBuss: MessageBuss

  constructor(injector:Injector) {
    this.messageBuss = injector.get(MessageBuss)
  }
}

class SomeSmartComponent extends SmartComponent {
  constructor(injector:Injector) {
    super.injector;
  }
}