angularangular2-servicesangular2-modules

How to share service between two modules - @NgModule in angular not between to components?


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.

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 ).

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?


Solution

  • 2021-02-03

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

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

    Original

    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 {}
    

    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.

    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
        }));
      }
    }
    

    See also How to dynamically create bootstrap modals as Angular2 components?