0

If I have a ParentService, who has a dependency on ChildService, you must list both the ParentService and ChildService in the "providers" attribute of the @Component definition.

Is there a way to implement ParentService so that it automatically injects ChildService so that components only need to reference ParentService?

kokokenada
  • 139
  • 1
  • 9

1 Answers1

1

In fact, the service needs to be visible from the injector of the component that executes the call. Injectors are linked to components only not services so no configuration can be done at this level.

By specifying services when bootstrapping your application, you won't have this problem:

bootstrap(AppComponent, [ ParentService, ChildService ]);

This question could interest you as well:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • 1
    Yeah - saw that article. My concern is that it requires a lot of knowledge of how ParentService works (e.g. what it's dependencies are) and, if those change in the future, users would need to make corresponding changes. – kokokenada May 30 '16 at 11:52
  • 1
    In fact, what I would do (and what libraries actually do) is to provide an array containing an array of consistent providers. For example `HTTP_PROVIDERS`. If you put `HTTP_PROVIDERS` in your providers (bootstrap or components), you're sure that you have all you need ;-) – Thierry Templier May 30 '16 at 11:56
  • OK, Cool! What's the syntax for providing the array of providers? – kokokenada May 30 '16 at 12:00
  • 1
    The way to create an array in JavaScript / TypeScript ;-) Here is a sample for your use case: `export var SOME_PROVIDERS = [ ParentService, ChildService ];`. And the way to use it in your application: `import {SOME_PROVIDERS} from './some.module'; boostrap(AppComponent, [ SOME_PROVIDERS ]);`. – Thierry Templier May 30 '16 at 12:03
  • And should also work with "providers: SOME_PROVIDERS", in an @Component as well, right? Odd I'm getting "Unhandled Promise rejection: Cannot read property 'parameters' of undefined", when I do. I must be doing something else wrong... (Thanks for all the help, BTW) – kokokenada May 30 '16 at 12:28
  • 2
    Ah never mind, got it. I had to have my 'export let SOME_PROVIDERS" after my class definition. – kokokenada May 30 '16 at 12:32