说我有一个非常基本的组件,它是Angular组件库的一部分,如下所示:
<div>
<a routerLink="/">
</div>
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'my-component',
templateUrl: './mycomponent.component.html'
})
export class MyComponentComponent implements OnInit {
@Input() title: string;
constructor() { }
ngOnInit() {
}
}
import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyComponentComponent} from './mycomponent.component';
@NgModule({
declarations: [MyComponentComponent],
imports: [
CommonModule,
RouterModule
],
exports: [MyComponentComponent]
})
export class MyComponentModule{ }
我现在发布此库,并在另一个项目中使用此组件,通过包含MyComponentModule如下:
@NgModule({
imports: [CommonModule, RouterModule, MyComponentModule],
declarations: []
})
export class MyProjectModule{}
然后我得到以下stacktrace:
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
,并且如果我添加了<a routerLink="/"></a>
也可以正常工作,但如果routerLink在来自外部库的子组件]内部,则它不起作用。导航可以在应用程序中的其他任何地方正常运行。这是怎么回事?
说我有一个非常基本的组件,它是Angular组件库的一部分,如下所示:mycomponent.module.html
一段时间后我找到了解决方案。