在 Angular 库中使用 RouterModule 时出现错误:NG0203

cub*_*ube 7 angular angular-router angular-library

我正在尝试创建一个 Angular v14 应用程序,该应用程序导入包含路由的 Angular 库。我的设置看起来像这样:

app.module.ts:(主应用程序)

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

test.module.ts(库)

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

当我运行ng serve所有内容时,编译时没有任何问题,但是打开时localhost:4200我发现一个空白页面,并在控制台中出现此错误:

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

如果我省略了RouterModule.forChild()错误test.module.ts就会消失,所以它一定与此相关(另外,堆栈跟踪引用RouterModule_Factory)。StoreModule.forFeature()当我尝试使用NGRX 时,我也遇到了同样的问题。我已确保使用所有相同版本的@angular/...,因为版本不匹配似乎在某些情况下会导致此错误,但这不会改变任何内容。

对我所缺少的有什么想法吗?

小智 0

我有同样的问题,但我不知道为什么,因为我的应用程序模块很好。

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import {MatDialogModule} from '@angular/material/dialog';
import { ToastrModule } from 'ngx-toastr';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { OrdersComponent } from './orders/orders.component';
import { OrderComponent } from './orders/order/order.component';
import { OrderItemsComponent } from './orders/order-items/order-items.component';



@NgModule({
  declarations: [
    AppComponent,
    OrdersComponent,
    OrderComponent,
    OrderItemsComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    MatDialogModule,
    ToastrModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule
  ],
  
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)