single spa - Angular - shared state

128 views Asked by At

In context of Single spa with angular, how can we resolve cross microfrontend runtime issues for services, modules, components etc. Example: I have microfront end 'container' which is always loaded and have some shared services, modules, components etc I'm using that shared stuff in another two micro frontends but getting angular errors while loading those micro frontends. errors such as: https://angular.io/errors/NG0203

Is there any recommendations for single spa with Angular which has shared state microfrontend as state management, which I can follow ?

I have resolved compile time reference issue as below: I have published library from container microfrontend which has all the shared models, services, components. And installed that as dev dependency in another micro frontend. I am also exporting few models, services from main.single-spa.ts of 'container' micro frontend to check whether it is resolving run time issues.

Now, regarding https://angular.io/errors/NG0203, if I need to use services across micro frontend how can we resolve or proceed with this issue ?

1

There are 1 answers

0
androbin On

Microfrontends can share libraries. Those can be defined in the build process. If you use Nx then the additionalShared setting might help you. The shared libraries are handled as a singleton. Any data stored there (it can be a global variable or any type of storage) is shared across the MFEs. Using Nx a locally-built-library can be shared, too. It can be imported to set the data in the host, and imported to get the data in the container/entry. additionalShared parameter is not needed to local nx libraries. It detects them automatically.

Other build systems have this option, too.

For the injection context: you need a component, a guard or a provider in the route. In the route config you can use inject in any of these:

const routes = [{
  component: MyComponent,
  providers: [MyService],
  canActivate: [() => {
    const service = inject(MyService);
    return true;
  }],
}];

This way in the MyService and MyComponent the injection can be used as you have used to it. The routes can be loaded as an MFE to a loadChildren of a route. Loading a standalone component as an MFE is not differ much, use the loadComponent of Angular 14.