我正在寻找一种生活在页面上的多个根组件之间进行交互的方式。背景是我正在为CMS开发一堆模块,如果用户决定将它们添加到页面中,它们应该能够共享数据,使用事件或彼此了解。由于CMS的性质,这些组件将独立引导。

在Angular 1中,存在使用JQuery获取控制器类的引用的可能性:

$("#MyApplication").controller();


Angular 2是否以某种方式提供了相似的方法甚至更好的方法来使它们彼此通信?

最佳答案

您可以使用共享服务。

class SharedService {
  ...
}

var sharedService = new SharedService();

bootstrap(App1, [provide(SharedService, {useValue: sharedService})]);
bootstrap(App2, [provide(SharedService, {useValue: sharedService})]);


在要与其他Angular应用程序通信的组件中,只需注入服务

constructor(private sharedService:SharedService) {
  sharedService.someObservable.subscribe(...);
  sharedService.someObservable.emit(...);
}

09-18 19:51