注入ElementRef导致无法避免的错误 [英] Injecting ElementRef to injecable error
问题描述
我在向Injectable
注入ElementRef
时遇到问题.这是我的代码:
I have an issue with injecting ElementRef
to my Injectable
. Here is my code:
import {Injectable, DynamicComponentLoader, ElementRef, Inject} from "angular2/core";
import {Modal} from './Modal';
@Injectable()
export class ModalService{
constructor(public _dcl:DynamicComponentLoader, public _el:ElementRef){
}
createModal(parent){
this._dcl.loadIntoLocation(Modal,this._el, 'modal')
}
}
我的Modal
:
从"angular2/core"导入{Component};
import {Component} from "angular2/core";
@Component({
selector: 'modal',
templateUrl: 'app/common/modal/Modal.html'
})
export class Modal{
constructor(){
}
}
这使我遇到以下错误:
没有ElementRef的提供者! (HomeComponent-> ModalService-> ElementRef)
No provider for ElementRef! (HomeComponent -> ModalService -> ElementRef)
为什么?
推荐答案
您不能将ElementRef
注入到服务类中,而只能注入到组件或指令中. ElementRef
注入一个实例,其中.nativeElement
指向组件或指令附加到的DOM元素,但没有用于服务的DOM元素.
You can't inject ElementRef
to a service class, only to a component or directive. ElementRef
injects an instance where .nativeElement
points to the DOM element the component or directive is attached to but there is no DOM element for a service.
在您的示例中,ElementRef
不能为任何 ElementRef
. ElementRef
确定将Modal
组件添加到DOM的位置.
In your example ElementRef
can't be any ElementRef
. The ElementRef
determines where you Modal
component is added to the DOM.
我建议您在DOM的某处添加一个单独的Modal
组件,以提供将内容显示为模式的服务.该组件将注入全局共享服务并订阅事件.
I suggest you add one single Modal
component somewhere to the DOM that provides the service of showing content as a modal. This component injects a globally shared service and subscribes to events.
其他想要使用Modal
组件的组件也注入了全局服务,并发出组件类型,供订阅Modal
组件接收,然后使用DynamicComponentLoader
来添加DynamicComponentLoader
将组件传递给自身以显示为模式.
Other components that want to use the Modal
component also inject the global service and emit a component type to be received by the subscribing Modal
component which then uses DynamicComponentLoader
to add the passed component to itself to be shown as modal.
有关更多详细信息,请参见 https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
For more details see https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
SO上也有几个类似的问题.
There are also several similar questions on SO already.
这篇关于注入ElementRef导致无法避免的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!