Skip to content

Injection Context for loadChildren and loadComponent functions #51532

Closed
@IKatsuba

Description

@IKatsuba

Which @angular/* package(s) are relevant/related to the feature request?

router

Description

What I have

  • host application
  • micro front-end applications that are loaded using loadChildren and loadConponent
  • localization using @angular/localize

Problem

Need to load micro-frontend module or component with host application locale.

The LOCALE_ID token is used to determine the current locale. The first thing that comes to mind is to use the inject function to get the token value from the injector.

{
  path: '...',
  loadChildren: () => loadRemoteModule(`module-${inject(LOCALE_ID)}`, 'Module')
}

But in the loadChildren and loadComponent functions, using the inject function causes an error.

NG0203: `inject()` must be called from an injection context, such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`.

Proposed solution

I propose to create an injection context for loadChildren and loadComponent functions when calling them

Alternatives considered

I am setting the locale to the window object as a fast solution.

{
      provide: APP_INITIALIZER,
      multi: true,
      useFactory: () => {
        const locale = inject(LOCALE_ID);
        const windowRef = inject(WINDOW);

        windowRef.__LOCALE_ID__ = AvailableLocales.includes(
          locale as AvailableLocale
        )
          ? locale
          : AvailableLocale.EN;
        return () => undefined;
      },
    }

And then load micro-frontend:

{
  path: '...',
  loadChildren: () => loadRemoteModule(
    `module_${window.__LOCALE_ID__}`,
    moduleName
  )
}

But for SSR, I will have to get another solution.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions