Angular 2 - Parent 和 children 通过服务进行通信
Angular 2 - Parent and children communicate via a service
这与食谱示例有关:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
我做了一个带有 observable 的服务,所以没有直接连接的组件可以通信。
当有一个真正的 孙子 连接到 observable 和一个 parent 谁在听。
当我尝试在没有 parent 的情况下创建 孙子 时出现问题("No provider for service"
).
如说明书中所述,服务应该仅在正在侦听的组件内作为提供者 providers: [MissionService]
。
这是因为您无法通过分层注入器利用提供程序。
完成这项工作的最简单方法是在引导应用程序时定义服务的提供者:
bootstrap(AppComponent, [ MissionService ]);
不要忘记从组件的提供者属性中删除服务。
这在组件链接在一起时有效,因为组件在其关联的注入器中查找提供程序。如果没有匹配,它会查看其父注入器等:
Application
|
AppComponent
|
ChildComponent
|
SubChildComponent
在一个组件中没有关联和定义提供者,其他组件将无法找到它。
关于分层注入器的模式细节,你可以看看这个问题:
- What's the best way to inject one service into another in angular 2 (Beta)?
这与食谱示例有关:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
我做了一个带有 observable 的服务,所以没有直接连接的组件可以通信。
当有一个真正的 孙子 连接到 observable 和一个 parent 谁在听。
当我尝试在没有 parent 的情况下创建 孙子 时出现问题("No provider for service"
).
如说明书中所述,服务应该仅在正在侦听的组件内作为提供者 providers: [MissionService]
。
这是因为您无法通过分层注入器利用提供程序。
完成这项工作的最简单方法是在引导应用程序时定义服务的提供者:
bootstrap(AppComponent, [ MissionService ]);
不要忘记从组件的提供者属性中删除服务。
这在组件链接在一起时有效,因为组件在其关联的注入器中查找提供程序。如果没有匹配,它会查看其父注入器等:
Application
|
AppComponent
|
ChildComponent
|
SubChildComponent
在一个组件中没有关联和定义提供者,其他组件将无法找到它。
关于分层注入器的模式细节,你可以看看这个问题:
- What's the best way to inject one service into another in angular 2 (Beta)?