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

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

问题描述

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

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?

推荐答案

2021-02-03

在最近的 Angular 版本中,这是使用 @Injectable({providedIn: 'platform'})

In recent Angular versions this is solved using @Injectable({providedIn: 'platform'})

https://angular.io/api/core/Injectable

原创

你可以在 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 发出值的方法,并且订阅者与发射者位于不同的应用程序中,则订阅者中的代码在发射器的 NgZone 中执行.

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中订阅一个observable时使用

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天全站免登陆