简体   繁体   English

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

[英]Angular 2 Component Interaction via a service

I have two parallel directives (as apposed to parent-child) and I want them to communicate via a service using observable if possible. 我有两个并行的指令(与父子指令并置),并且我希望它们在可能的情况下通过可观察的服务进行通信。 I've read the official component interaction guidline , but it talks about parent-child interaction. 我已经阅读了官方的组件交互指南 ,但是它谈到了父子交互。 I tried to make a plunker with two directives but it doesn't work. 我试图用两个指令来制作一个pl节的人 ,但它不起作用。

Basically, what I want is to create a service: 基本上,我想要创建一个服务:

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

And then, use this service to make a bridge between < dir1 > and < dir2 >. 然后,使用此服务在<dir1>和<dir2>之间建立桥梁。 Could someone point out how to implement this senerio? 有人可以指出如何实施这项战略吗?

Btw, I choose to use observable mainly because: 顺便说一句,我选择使用observable主要是因为:

  • I read the post in this thread . 我在此主题中阅读了该帖子
  • If I want many directives to communicate, I guess observable could make the logic more clear. 如果我想传达许多指令,我想可以观察到的可以使逻辑更清晰。

Thanks! 谢谢!

If you add the "shared" service to providers of each component 如果将“共享”服务添加到每个组件的providers

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

then for each component a new instance is maintained. 然后为每个组件维护一个新实例。

To get a shared service you either add it only in bootstrap(AppComponent, [DirService]) or one common ancestor of the components and directives that defines the root component and the scope of the shared service. 要获得共享服务,您可以仅将其添加到bootstrap(AppComponent, [DirService])或者将其定义为共享服务的根组件和范围的组件和指令的一个共同祖先。
This way every descendant gets the same instance. 这样,每个后代都会获得相同的实例。

Plunker example 柱塞示例

See also 也可以看看
- AngularJs 2 - multiple instance of service created -AngularJs 2-创建了多个服务实例
- How to use Dependency Injection (DI) correctly in Angular2? - 如何在Angular2中正确使用依赖注入(DI)?

You need to specify the DirService service when bootstrapping your application: 引导应用程序时,需要指定DirService服务:

bootstrap(AppComponent, [ DirService ]);

And remove it from component providers attribute: 并将其从组件提供者属性中删除:

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

This way you will share the same instance of the service for the whole application (and both components). 这样,您将为整个应用程序(和两个组件)共享服务的相同实例。

See this plunkr: http://plnkr.co/edit/rYq3iicbd4mKGyxHlJmg?p=preview . 请参阅以下代码: http ://plnkr.co/edit/rYq3iicbd4mKGyxHlJmg?p=preview。

This behavior is linked to the "hierarchical injectors" of Angular2 dependency injection. 此行为与Angular2依赖项注入的“分层注入器”相关联。

For more details, you could have a look at this question: 有关更多详细信息,您可以看一下这个问题:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM