Angular 2 通过服务进行组件交互

Angular 2 Component Interaction via a service

我有两个并行指令(与父子指令相对),如果可能的话,我希望它们通过使用 observable 的服务进行通信。我已经阅读了带有两个指令的 official component interaction guidline, but it talks about parent-child interaction. I tried to make a plunker 但它不起作用。

基本上,我想要的是创建一个服务:

export class DirService {
   contentSource = new Subject();
   content$ = this.contentSource.asObservable();
}

然后,使用此服务在 之间架起一座桥梁。有人可以指出如何实现这个 senerio 吗?

顺便说一句,我选择使用 observable 主要是因为:

谢谢!

您需要在引导应用程序时指定 DirService 服务:

bootstrap(AppComponent, [ DirService ]);

并将其从组件提供者属性中删除:

@Component({
  (...)
  //providers: [ DirService ]
})

这样您将为整个应用程序(以及两个组件)共享同一个服务实例。

看到这个 plunkr:http://plnkr.co/edit/rYq3iicbd4mKGyxHlJmg?p=preview

此行为与 Angular2 依赖注入的 "hierarchical injectors" 有关。

更多细节,你可以看看这个问题:

  • What's the best way to inject one service into another in angular 2 (Beta)?

如果将 "shared" 服务添加到每个组件的 providers

@Component({
    selector: 'dir2',
    template: '{{field}}',
    providers: [DirService]
})

然后为每个组件维护一个新实例。

要获得共享服务,您可以仅将其添加到 bootstrap(AppComponent, [DirService]) 中,或者添加定义根组件和共享服务范围的组件和指令的共同祖先。
这样每个后代都会得到相同的实例。

Plunker example

另见
- AngularJs 2 - multiple instance of service created
-