NG0203: inject() must be called from an injection context such as a constructor, a factory...

Discussão em 'Angular' iniciado por mideo mideo, Dezembro 21, 2024.

  1. mideo mideo

    mideo mideo Guest

    Title: Angular 18: Dynamic Microfrontend Loading with Native Federation - NG0203 Error

    Question:

    I am trying to dynamically load a microfrontend component in an Angular 18 app using angular native federation and the loadRemoteModule method. The goal is to load a remote module from another Angular app and display it as a custom element (use the remote component so i can pass input and receive events from the component). However, I am encountering the following error:

    ERROR RuntimeError: 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`. Find more at https://angular.dev/errors/NG0203


    Here is the code for my setup:

    app.component.ts:

    import { loadRemoteModule } from '@angular-architects/native-federation';
    import { Component, Injector, OnInit } from '@angular/core';
    import { createCustomElement } from '@angular/elements';

    @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    export class AppComponent implements OnInit {
    constructor(private injector: Injector) { }

    ngOnInit() {
    this.loadMicroFrontend();
    }

    loadMicroFrontend() {
    loadRemoteModule({
    remoteEntry: 'http://localhost:4202/remoteEntry.json', // Ensure this matches the remote setup
    remoteName: 'mfe2',
    exposedModule: './ExposeUserName'
    })
    .then((MicroModule: any) => {
    const ce = createCustomElement(MicroModule.ExposedUserNameComponent, {
    injector: this.injector
    });

    if (!customElements.get('app-expose-user-name')) {
    customElements.define('app-expose-user-name', ce);
    }
    })
    .catch((err: any) => console.error('Error loading remote module:', err));
    }
    }


    app.component.html:

    <app-expose-user-name [name]="'John Doe'"></app-expose-user-name>


    Problem:

    • I am getting the NG0203 error, which indicates an issue with the inject() function being used outside of an injection context.
    • I am using Angular 18 and @angular-architects/native-federation for microfrontend integration.
    • The remote module is being loaded correctly, but the error prevents it from rendering as a custom element.

    Question: How can I resolve the 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 and show the remote component successfully in Angular 18?

    Continue reading...

Compartilhe esta Página