更新:
@Injectable()
class MyService {
private renderer: Renderer2;
constructor(rendererFactory: RendererFactory2) {
this.renderer = rendererFactory.createRenderer(null, null);
}
}
这里有更多相关内容:https://github.com/angular/angular/issues/17824#issuecomment-351961146
之前的版本:
根据你的导入
import { Injectable, Renderer2 } from '@angular/core'
I suspect that you're trying to inject
Renderer2
in your service class. It won't work. You can't inject
Renderer2
in a service. It should work for components and services that are provided within a component.
We can take a look at the source code
https://github.com/angular/angular/blob/4.0.1/packages/core/src/view/provider.ts#L363-L373.
while (view) {
if (elDef) {
switch (tokenKey) {
case RendererV1TokenKey: {
const compView = findCompView(view, elDef, allowPrivateServices);
return createRendererV1(compView);
}
case Renderer2TokenKey: {
const compView = findCompView(view, elDef, allowPrivateServices);
return compView.renderer;
}
它仅在元素注入器树中检查。在此令牌可以提供的其他位置没有其他地方。
因此,在调用某些服务方法时,您必须从组件传递Renderer2到服务中
https://github.com/angular/angular/issues/17824#issuecomment-311986129
或者您可以在组件内提供服务。
@Injectable()
export class Service {
constructor(private r: Renderer2) {}
}
@Component({
selector: 'my-app',
templateUrl: `./app.component.html`,
providers: [Service]
})
export class AppComponent {
constructor(private service: Service) {}
}