该代码在 Angular 版本 8.3.4 上运行良好,但是当我将其更新到最新版本的 Angular ( 9 ) 时,出现以下错误
以下是堆栈跟踪
core.js:3866 ERROR Error: Uncaught (in promise): Error: Multiple components match node with tagname app-lobby
Error: Multiple components match node with tagname app-lobby
at throwMultipleComponentError (core.js:5511)
at findDirectiveDefMatches (core.js:8276)
at resolveDirectives (core.js:8080)
at elementStartFirstCreatePass (core.js:14215)
at ɵɵelementStart (core.js:14249)
at Module.ɵɵelement (core.js:14324)
at MainComponent_Template (main.component.html:1)
at executeTemplate (core.js:7562)
at renderView (core.js:7387)
at renderComponent (core.js:8577)
at resolvePromise (zone.js:836)
at resolvePromise (zone.js:795)
at zone.js:897
at ZoneDelegate.invokeTask (zone.js:431)
at Object.onInvokeTask (core.js:27769)
at ZoneDelegate.invokeTask (zone.js:430)
at Zone.runTask (zone.js:198)
at drainMicroTaskQueue (zone.js:611)
at ZoneTask.invokeTask (zone.js:517)
at ZoneTask.invoke (zone.js:502)
我有完全相同的错误说Error: Multiple components match node with tagname <my-tagname>
我检查了很长时间才发现这个标签实际上是唯一的。在第二次阅读这个问题和所有答案后,我找到了 @Eugen 对原始问题的评论,这最终对我有帮助。所以我在这里添加一个小例子,以防将来每个人都遇到这个问题。 Angular 的错误消息在这里并没有真正的帮助。
我的错误是我将一个服务注入到我的组件中并直接在构造函数中使用它,如下所示:
constructor(private myService: MyService) {
this.myService.doSomething()
}
这不起作用,因为它在 Angular 的依赖注入和我想要在构造函数中使用该服务之间引入了竞争条件。在构造函数内部,服务尚未实例化。
你想要做的是在调用构造函数之后使用该服务,即在 Angular 的 OnInit-hook 中:
export class MyComponent implements OnInit {
constructor(private myService: MyService) {}
ngOnInit(): void {
this.myService.doSomething();
}
// Rest of the component
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)