【问题标题】:Error: NG0203 when using RouterModule in Angular library错误:在 Angular 库中使用 RouterModule 时出现 NG0203
【发布时间】:2022-11-07 09:45:43
【问题描述】:

我正在尝试创建一个 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 { }

测试模块.ts(图书馆)

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

当我运行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`.

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

关于我所缺少的任何想法?

【问题讨论】:

  • 你的 TestComponent 组件里面有什么?你可以发布代码吗?
  • @VasileiosKagklis 它只是一个标准生成的 Angular 组件,没有任何修改。我可以稍后发布代码。

标签: angular angular-router angular-library


【解决方案1】:

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

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 { }

【讨论】:

    猜你喜欢
    • 2016-04-14
    • 2021-04-26
    • 2021-11-18
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 2022-12-19
    • 2016-07-25
    相关资源
    最近更新 更多