0

This is connected to an cookbook example : https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

I made a service with an observable, so components that are not directly connected can communicate.

Everything works nicely when there is an actual grandchild who is hooked to the observable and a parent who is listening.

My problem appears when I try to create the grandchild without a parent who is listening ("No provider for service").

Like in the cookbook, the service should be a provider only inside a component that is listening providers: [MissionService].

Luka Šilje
  • 605
  • 2
  • 8
  • 19

1 Answers1

1

It's because you can't leverage the provider through the hierarchical injectors.

The easiest way to make this work is to define the provider for the service when bootstrapping the application:

bootstrap(AppComponent, [ MissionService ]);

Don't forget remove the service from the providers attribute of components.

This works when components have links together because a component looks for providers in its associated injector. If there is no match, it looks into its parent injector and so on:

Application
     |
AppComponent
     |
ChildComponent
    |
SubChildComponent

With no relation and defining provider in a component, the other component won't be able to find it.

For mode details about hierarchical injectors, you could have a look at this question:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Thank you for the smooth explanation! By the way, it seems like I'm slacking behind you guys on Angular 2 knowledge, how do you guys know so much? Where do you look for answers (stackoverflow excluded)? – Luka Šilje Apr 10 '16 at 21:15
  • We now have Angular 2 live and Angular 4 at the door step.. Is this still valid? – Abdel Raoof Olakara Mar 05 '17 at 19:00