Angular 需要路由模块的外部组件

Angular 需要路由模块的外部组件,angular,typescript,angular-routing,angular8,Angular,Typescript,Angular Routing,Angular8,假设我有一个非常基本的组件,它是角度组件库的一部分,如下所示: mycomponent.module.html mycomponent.component.ts 从'@angular/core'导入{Component,OnInit,Input}; @组成部分{ 选择器:“我的组件”, templateUrl:“./mycomponent.component.html” } 导出类MyComponentComponent实现OnInit{ @输入标题:字符串; 构造函数{} 恩戈尼特{ } }

假设我有一个非常基本的组件,它是角度组件库的一部分,如下所示:

mycomponent.module.html mycomponent.component.ts 从'@angular/core'导入{Component,OnInit,Input}; @组成部分{ 选择器:“我的组件”, templateUrl:“./mycomponent.component.html” } 导出类MyComponentComponent实现OnInit{ @输入标题:字符串; 构造函数{} 恩戈尼特{ } } mycomponent.module.ts 从'@angular/router'导入{RouterModule}; 从“@angular/core”导入{NgModule}; 从“@angular/common”导入{CommonModule}; 从“./mycomponent.component”导入{mycomponent}; @NGD模块{ 声明:[MyComponentComponent], 进口:[ 公共模块, 路由模块 ], 导出:[MyComponentComponent] } 导出类MyComponentModule{} 我现在发布此库,并在另一个项目中使用此组件,包括MyComponentModule,如下所示:

myproject.module.ts @NGD模块{ 导入:[CommonModule、RouterModule、MyComponentModule], 声明:[] } 导出类MyProjectModule{} 然后,我得到以下堆栈跟踪:

ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[RouterLinkWithHref -> Router]: 
  StaticInjectorError(Platform: core)[RouterLinkWithHref -> Router]: 
    NullInjectorError: No provider for Router!
NullInjectorError: StaticInjectorError(AppModule)[RouterLinkWithHref -> Router]: 
  StaticInjectorError(Platform: core)[RouterLinkWithHref -> Router]: 
    NullInjectorError: No provider for Router!
    at NullInjector.get (vendor.js:131635)
    at resolveToken (vendor.js:146553)
    at tryResolveToken (vendor.js:146479)
    at StaticInjector.get (vendor.js:146329)

尽管MyProjectModule使用RouterModule,并且在添加时可以正常工作,但如果routerLink位于外部库的子组件内,则它无法工作。导航在应用程序中的任何其他位置都能正常工作。这是怎么回事?

过了一会儿,我找到了解决办法

如果需要服务注入(例如路由),请不要导入tsconfig.json中包含路径的外部库

包含MyComponentModule的外部库是使用tsconfig.json中的Path对象人工导入的,例如:


虽然在修改库时通过热加载我的应用程序使开发变得更容易,但它会阻止模块被正确注入。

我认为您可能需要在MyProjectModule中使用BrowserModule。它已经存在,尽管在另一个模块中,由于MyProjectModule不是根模块-错误消息听起来似乎与路由相关,这可能是一件愚蠢的事情,但是您的路由是否为RouterModule设置了/使用了RouterModule?遗憾的是,它是…:这可能有帮助吗
"paths": {
  "my-library": ["../my-library/lib/src/"]
}