1

I´m decomposing an Angular web in several microfrontends. One of these microfrontend handles the shopping cart, and it has a service to store products that have been added. My shell microfrontend needs to use that service to show in a icon how many items are in the car, add new items, etc.

Can I use a service in a microfrontend that is stored in a different microfrontend?

I´m using this tutorial, but it only explains how to route a page that are in another microfrontend.

Thanks.

R. Richards
  • 24,603
  • 10
  • 64
  • 64

2 Answers2

4

Can I use a service in a microfrontend that is stored in a different microfrontend?

No. Code in your microfront end is not shared among each other.

You need to create a library project within your repository. This library will be shared among your micro-apps. Here you can create a service which will be used to store some data & share it among apps.

https://angular.io/guide/creating-libraries

Is using Nx Workspace: https://nx.dev/workspace/library

Pankaj Sati
  • 2,441
  • 1
  • 14
  • 21
  • The project library does not need to be in the same repository, the OP also can install it on both MFE using NPM. If OP want to share data between the 2 MFE, a singleton is needed and for that it is necessary to add it to the `shared` property on the `webpack.config.js` file. – David Fontes Feb 02 '22 at 18:12
  • Could you please check this question https://stackoverflow.com/questions/75958591/nx-mfe-angular-module-federation-not-able-to-access-remote-micro-front-end – Pranav MS Apr 09 '23 at 06:13
0

You can do this.

// In your remote module
@NgModule({
  declarations: [],
  imports: [CommonModule],
  providers: [YourRemoteService],
})
export class YourRemoteModuleModule {
  public constructor(
    @Inject(YourRemoteService) private readonly yourRemoteService: YourRemoteService
  ) {}

  /**
   * Allows the to access YourRemoteService.
   *
   * @returns The service instance.
   */
  public getService(): YourRemoteService {
    return this.yourRemoteService;
  }
}

// In the module that wants to load a remote module/service
import { loadRemoteModule } from '@angular-architects/module-federation';
import type { LoadRemoteModuleOptions } from '@angular-architects/module-federation';

const options: LoadRemoteModuleOptions = {
  remoteEntry: // your entry
  remoteName: // your remote name
  exposedModule: // your exposed module
};

from(loadRemoteModule(options)).pipe(
  switchMap((module) => this.compiler.compileModuleAsync<YourContract>(module[YourModule])),
  map((moduleFactory) => {
   const moduleRef = moduleFactory.create(this.injector);
   const instance = moduleRef.instance;
   return instance.getService(); // Your contract
 });
Vasily Ivanov
  • 351
  • 3
  • 5