Error: NG0203 when using RouterModule in Angular library

Viewed 34

I'm trying to create an Angular v14 application that imports an Angular library that contains routing. My setup looks something like this:

app.module.ts: (Main app)

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot([
      {path: '' , loadChildren: () => import('@mytest/core').then(m => m.TestModule)}
    ])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

test.module.ts (Library)

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild([
      {path: '', pathMatch: 'full', component: TestComponentComponent}
    ]),
  ],
  declarations: [TestComponentComponent],
  exports: [TestComponentComponent],
})
export class TestModule { }

When I run ng serve everything compiles without any issue, however opening localhost:4200 I find a blank page and this error in the console:

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`.

If I omit the RouterModule.forChild() in test.module.ts the error dissappears, so it must be related to that (also, the stacktrace references RouterModule_Factory). I also have the same issue with the NGRX StoreModule.forFeature() when I try to use that. I've made sure to use all the same versions of @angular/..., since a version mismatch seems to cause this error in some instances, but that doesn't change anything.

Any ideas on what I'm missing?

0 Answers
Related