In an Angular app I need to show a popup message when a remote module fails to load (e.g. the target micro frontend is offline).
As the text is localized, I'd try to use the inject()
method in the "field initializer" case to create an instance of the TranslatePipe.
const handleLoadError = () => {
const translatePipe = inject(TranslatePipe); // <---
const targetData = {
content: translatePipe.transform('MESSAGE')
};
// Show popup ...
}
const routes: Routes = [
{
path: 'home',
loadChildren: () => loadRemoteModule('targetUrl/home.js')
.then((m) => m.AppModule)
.catch(() => {
handleLoadError();
})
}
];
@NgModule({
imports: [
RouterModule.forRoot(routes),
],
exports: [RouterModule],
})
export class AppRoutingModule {}
However, it seems this is not accepted as I get the following error:
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
`EnvironmentInjector#runInContext`.
UPDATED
After debugging the framework, I could see that the exception occurs in the Angular core.js
file in the following part. In my case, _currentInjector
is not set and triggers an exception.
/**
* Current injector value used by `inject`.
* - `undefined`: it is an error to call `inject`
* - `null`: `inject` can be called but there is no injector (limp-mode).
* - Injector instance: Use the injector for resolution.
*/
let _currentInjector = undefined;
function setCurrentInjector(injector) {
const former = _currentInjector;
_currentInjector = injector;
return former;
}
function injectInjectorOnly(token, flags = InjectFlags.Default) {
if (_currentInjector === undefined) {
throw new RuntimeError(-203 /* RuntimeErrorCode.MISSING_INJECTION_CONTEXT */, ngDevMode &&
`inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with \`EnvironmentInjector#runInContext\`.`);
}
//...