Reputation: 605
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]
.
Upvotes: 0
Views: 1249
Reputation: 202196
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:
Upvotes: 1