Rohith S. Ranade
Rohith S. Ranade

Reputation: 191

sharing a single service across multiple angular 5 applications

I'm running multiple small angular 5 applications as widgets inside my backbase application. Now I'm trying to write a global service, which is at window level, and share across all applications.

Currently, I'm making the service static and using in each widget and using webpack to create widget specific bundle. Here I was able to achieve http caching with rxjs operators.

But I feel this might not be the right way to implement it. Is there any better way to share a singleton service across multiple angular 5 applications in a single project.

Upvotes: 19

Views: 4321

Answers (3)

Xinan
Xinan

Reputation: 3162

Previously if you want to share something between multiple Angular projects that was pretty tricky. You'll have to do one of the following:

  • Create a package contains shared code and publish it to private or public NPM registry
  • Create a GIT submodule and reference it on both of your projects

But now I'm guessing the Library support introduced in Angular 6 would suits your needs the best.

For details see: Angular - Creating Libraries

It's similar to publish your shared package to NPM but Angular CLI (and ng-packagr) really made it super simple.

Upvotes: 6

kemsky
kemsky

Reputation: 15261

Technically one of your modules ("main" module) can export its own service via window object, other modules ("clients") can inject wrapper service:

class ServiceWrapper implements IService
{
    private readonly instance:IService;

    constructor(){
        this.instance = window['myService'] as IService;
    }

    public someMethod():void {
         this.instance.someMethod();
    }
}

Upvotes: 4

Théo T. Carranza
Théo T. Carranza

Reputation: 8449

By definition, services are singletons, so if you need a service to be used across multiple apps inside a project, all you really need to do is define it on the root of your project, and import it in each app.module. What is a bit unorthodox here is the idea of using multiple apps. Maybe what you really need is one app, with as many modules as your solution requires. But then again, without looking at your architecture I can't say anything with good accuracy, so if you want to share your code, maybe I can take a look at it and make a suggestion.

Cheers!

Upvotes: 3

Related Questions