Angular NullInjectorError:R3InjectorError(AppModule)[路由器->;路由器->;路由器]:NullInjectorError:没有路由器的提供程序
我有一个已发布的库,其中包含一个在其模板中使用[routerLink]的组件。在我的应用程序中安装库之后,我得到错误NullInjectorError:R3InjectorError(AppModule)[路由器->路由器->路由器]: NullInjectorError:没有路由器的提供程序强> 在库中的模块内,将导入RouterModule,如下所示:Angular NullInjectorError:R3InjectorError(AppModule)[路由器->;路由器->;路由器]:NullInjectorError:没有路由器的提供程序,angular,Angular,我有一个已发布的库,其中包含一个在其模板中使用[routerLink]的组件。在我的应用程序中安装库之后,我得到错误NullInjectorError:R3InjectorError(AppModule)[路由器->路由器->路由器]: NullInjectorError:没有路由器的提供程序 在库中的模块内,将导入RouterModule,如下所示: @NgModule({ declarations: [ Component ], exports: [ Compon
@NgModule({
declarations: [
Component
],
exports: [
Component
],
imports: [
CommonModule,
RouterModule,
TranslateModule
]
})
export class LibWithComponentModule {
}
declarations: [
AppComponent,
RootComponent
],
imports: [
BrowserModule,
AppRoutingModule,
LibWithComponentModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
在我的应用程序中,RouterModule的配置如下:
const routes: Routes = [{
path: '',
component: RootComponent
}];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.module.ts
如下所示:
@NgModule({
declarations: [
Component
],
exports: [
Component
],
imports: [
CommonModule,
RouterModule,
TranslateModule
]
})
export class LibWithComponentModule {
}
declarations: [
AppComponent,
RootComponent
],
imports: [
BrowserModule,
AppRoutingModule,
LibWithComponentModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
但我以为会提供RouterModule?我做错了什么?我正面临着与您在我正在开发的大型应用程序中描述的完全相同的场景。我的主应用程序导入一个已发布的npm组件包,其中包含一个利用
routerLink
指令的组件。在运行应用程序时,我遇到了与您提到的相同的R3InjectorError
,尽管RouterModule
确实正确地导入到了所有需要它的模块中
在我的例子中,问题的根本原因是,这个npm包明确地将@angular/router
列为依赖项之一,而不是对等依赖项
(在库的情况下,它应该是这样的)。这意味着@angular/router
将安装在您的节点单元
中,以及节点单元/库/节点单元
中
发生的情况是,在运行时,发布的组件使用的RouterModule
与应用程序使用RouterModule.forRoot()提供的RouterModule
具有不同的InjectionToken
。发布的组件的RouterModule
指的是node\u modules/LIBRARY\u NAME/node\u modules/@angular/router
,而主应用程序提供了node\u modules/@angular/router
中的组件
因此,总而言之:修复方法是不要在库中明确地将任何@angular
包列为依赖项,而是正确地将它们标记为对等依赖项。下面介绍如何从ng packagr
文档中管理依赖项
仅供参考:我不确定这是否与常春藤有关,但在我的场景中,我运行Angular 11时启用了常春藤
在这种情况下,错误消息肯定非常混乱,因为注入的服务被命名为Router
两次,即使它们引用了不同的实例
希望这也能解决你的问题,我花了不少时间来解决这个问题 如果存在路由文件LibWithComponentModule
,您可以发布路由文件的代码吗?没有路由文件,我只使用LibWithComponent中的[routerLink]指令。对于库,如果它要导入到现有的应用程序中,通常情况下,您不应该导入浏览器模块,而是使用common模块。此外,还应使用forchild导入Routermodule。Forroot仅用于根模块。在这种情况下,我只需要路由器模块提供的模板指令,而不是更多或更少,因此我根本不使用forChild。这可能是问题吗?不,使用forChild似乎不是解决问题的方法。现在lib的构建失败了,消息是:decorators中不支持函数调用,但调用了“RouterModule”。