如何在两个模块之间共享服务-@NgModule不在组件之间成角度? [英] How to share service between two modules - @NgModule in angular not between to components?

查看:46
本文介绍了如何在两个模块之间共享服务-@NgModule不在组件之间成角度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有两个不同的引导程序模块(@NgModule)在一个应用程序中独立运行.没有一个单独的角度应用程序单独的引导程序模块,现在我希望它们应该相互通信并共享数据.

In my application, I have two different bootstrap module (@NgModule) running independently in one application. There are not one angular app bit separate bootstrap module and now I want they should communicate to each other and share data.

我知道通过@Injectable服务作为模块中的提供者,我可以在@NgModule下的所有组件中共享数据,但是我将如何在两个不同模块(而不是模块内部的组件)之间共享数据.

I know through @Injectable service as the provider in the module, I can share data in all component under @NgModule but how I will share data between two different module ( not component inside module ).

是否有一种方法可以在另一个模块中访问一个服务对象?有什么方法可以访问浏览器内存中可用的Service对象,并将其用于我的其他angular模块?

Is there a way one service object can be accessed in another module? Is there a way I can access the object of Service available in browser memory and use it in my other angular module?

推荐答案

您可以在Angular之外实例化服务并提供值:

You can instantiate a service outside Angular and provide a value:

class SharedService {
  ...
}

window.sharedService = new SharedService();

@NgModule({
  providers: [{provide: SharedService, useValue: window.sharedService}],
  ...
})
class AppModule1 {}

@NgModule({
  providers: [{provide: SharedService, useValue: window.sharedService}],
  ...
})
class AppModule2 {}

如果一个应用程序更改了SharedService中的状态或调用了导致Observable发出值的方法,并且订阅者所在的应用程序与发射器不同,则订阅者中的代码将在发射器.

If one application change the state in SharedService or calls a method that causes an Observable to emit a value and the subscriber is in a different application than the emitter, the code in the subscriber is executed in the NgZone of the emitter.

因此,当订阅SharedService中的可观察对象时使用

Therefore when subscribing to an observable in SharedService use

class MyComponent {
  constructor(private zone:NgZone, private sharedService:SharedService) {
    sharedService.someObservable.subscribe(data => this.zone.run(() => {
      // event handler code here
    }));
  }
}

另请参见如何动态创建引导模态作为Angular2组件?

这篇关于如何在两个模块之间共享服务-@NgModule不在组件之间成角度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆