如果同时在HTML中包含组件以及通过DI注入组件,为什么会出现StaticInjector错误 [英] Why do I get StaticInjector error if I include a component both in HTML as well as inject it via DI

查看:46
本文介绍了如果同时在HTML中包含组件以及通过DI注入组件,为什么会出现StaticInjector错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用LoginFormComponent的组件ValidateSessionComponent.我通过在ValidateSessionComponent的HTML中包含LoginFormComponentValidateSessionComponent中使用LoginFormComponent.

I have a component ValidateSessionComponent which uses LoginFormComponent. I use LoginFormComponent in ValidateSessionComponent by including it in the HTML of the ValidateSessionComponent.

到目前为止,这个方法工作正常.然后,我决定通过DI在ValidateSessionComponent

This works fine so far. Then I decided to also include reference of LoginFormComponent via DI in ValidateSessionComponent

constructor(private loginForm2:LoginFormComponent,private helper:HelperService,private dialogService:DialogBoxService,private activatedRoute:ActivatedRoute, private router:Router, private userManagementService:UserManagementService) { }

这开始导致错误StaticInjectorError(DynamicTestModule)[ValidateSessionComponent -> LoginFormComponent]: StaticInjectorError(Platform: core)[ValidateSessionComponent -> LoginFormComponent]: NullInjectorError: No provider for LoginFormComponent!

This started causing the error StaticInjectorError(DynamicTestModule)[ValidateSessionComponent -> LoginFormComponent]: StaticInjectorError(Platform: core)[ValidateSessionComponent -> LoginFormComponent]: NullInjectorError: No provider for LoginFormComponent!

为什么我开始出现错误?

Why do i start getting the error?

推荐答案

因为DI仅适用于提供者.

Because DI works only for providers.

组件不是提供程序.

如果希望获得对子元素的引用,请改用ViewChild.

If you wish to get a reference to your child element, use a ViewChild instead.

@ViewChild(LoginFormComponent, { static: true }) loginForm: LoginFormComponent;

这篇关于如果同时在HTML中包含组件以及通过DI注入组件,为什么会出现StaticInjector错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆