3

I have been reading the angular 9 documentation, and it states you can use the provideIn: 'platform' to share a singleton service across two angular applications, but I was not able to find a good example and the documentation is not clear about how to do it.

Supposing I have application1 with a service1 and application2 with a service2, and I want to somehow call a method of service2 from service1.

How can I make that "call"? should I somehow require or import the application2 into the application1?

caraie
  • 1,094
  • 7
  • 18
  • The scenario you describe isn't relevant to the use of `providedIn`. `providedIn` refers to how "shared" instances of any given service are. For example, `providedIn: 'root'` means one instance is shared in the app. `providedIn: 'platform'` means one instance is shared in multiple apps. – Kurt Hamilton Apr 09 '20 at 06:50
  • @KurtHamilton - I am trying to understand how to share single instance between an Angular Element and Angular SPA using `providedIn: platform`. https://medium.com/@sistla.kashyap/hello-alain-38926bedc759#--responses https://medium.com/@sistla.kashyap/hello-alain-840165647255 – Kashyap Jun 21 '20 at 21:42

1 Answers1

1

If you really need it running and don't care about it being pretty, you can always bind it to 'window'

import { Injectable } from '@angular/core';
@Injectable({
    providedIn: 'platform'
})
export class MySharedService {
    private _value = 0;
    constructor() {
        if (!!(<any>window).sharedService) return (<any>window).sharedService;
            (<any>window).sharedService = this;
    }
    
}

this way you can be sure that your service is going to be instantiated only once and your modules are actually going to be able to share it.