0

I have a service declared in my module.ts file to have an application-wide scope. The way to access the instance of this service is to declare it as part of the constructor for the component class, like so, and the framework automatically wires it up:

export class ComponentBase implements OnInit {

  constructor(private myService: MyService) { }
}

My component class is one of several similar components, so they all share a common base class, and this constructor is on the base. I discovered that base constructors are not automatically required, so it is possible that a derived class ends up without a constructor (and without the dependency).

So, is there another, more foolproof way to do it in the base class?

11
  • I don't understand exactly what you are trying to do. If you want all the derived classes to have access to the service, you can declare it as protected in the base class constructor. Commented May 15, 2018 at 22:11
  • @ConnorsFan It doesn't matter whether protected or private, it will not exist so long as the derived class fails to call the super(...) constructor. Commented May 15, 2018 at 22:12
  • But the base class constructor will be called if the derived class has no constructor. You talk about derived classes with a constructor but where super(...) is not called? Commented May 15, 2018 at 22:24
  • @ConnorsFan - apparently that is not the case. If there is no constructor in the derived class, then the base class constructor is not being called. I confirmed this through console.log. I originally thought otherwise, which is why the bug took a long time for me to track down. Commented May 15, 2018 at 22:25
  • I don't know how you implemented it, but it does work. Take a look at this stackblitz, where the HelloComponent is derived from the BaseComponent. Commented May 15, 2018 at 22:37

1 Answer 1

1

The injections are provided as a constructor parameters: - you can set the class directly, like this:

constructor(private myService: MyService)
  • or using the injector:

    constructor(injector: Injector){ this.myService = injector.get(MyService); }

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

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.