Daniel Morcillo
Daniel Morcillo

Reputation: 55

Angular Module Federation and remote services

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.

Upvotes: 2

Views: 5858

Answers (2)

Vasily Ivanov
Vasily Ivanov

Reputation: 380

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

Upvotes: 0

Pankaj Sati
Pankaj Sati

Reputation: 2529

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

Upvotes: 5

Related Questions