Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 584
Rohith S. Ranade Avatar asked Jul 27 '18 20:07

Rohith S. Ranade


People also ask

How do I share a component between Angular projects?

To get started, go ahead and install bit-cli, then head over to the project from which to share the components, and initialize a bit workspace. Then, head over to bit. dev and create a free account. Then, create a collection to host your shared components.

Can multiple angular applications be bootstrapped using same element?

ans : only one angularjs application can be auto-bootstrapped. the first 'ng-app' found in the document will be used to define the root element to auto-bootstrap as an application. to run multiple applications in an html document, one must manually bootstrap them using angular bootstrap service.

Can we have multiple app modules in angular?

So now, you need to follow some simple steps to use multiple modules in an Angular application. Create a simple application using Angular CLI. If you are going to use Angular for the first time, click here. I am going to create an application which contains three modules: App, Employee, Admin, Home.


2 Answers

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.

like image 171
Xinan Avatar answered Oct 10 '22 08:10

Xinan


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();
    }
}
like image 32
kemsky Avatar answered Oct 10 '22 08:10

kemsky