在Angular 4中使用渲染器 [英] Using Renderer in Angular 4
问题描述
我了解为什么最好使用渲染器而不是直接在Angular2项目中操纵DOM.但是,我已经卸载,清除缓存,重新安装了Node,Typescript和Angular-CLI几次,尝试注入Renderer时仍然出现错误.
I understand why it's better to use renderer instead of directly manipulating the DOM in Angular2 projects. However, I have uninstalled, clear cache, reinstalled Node, Typescript and the Angular-CLI several times and I still get an error when trying to inject the Renderer.
import { Injectable, Renderer2 } from '@angular/core';
constructor(private renderer: Renderer2) {}
__ zone_symbol__消息:"Renderer2没有提供者!"
__zone_symbol__message: "No provider for Renderer2!"
__ zone_symbol__stack:Error↵出现在Error.ZoneAwareError
__zone_symbol__stack:"Error↵ at Error.ZoneAwareError
有人知道我在做什么错吗?
Does anyone have any ideas what I am doing wrong?
推荐答案
更新:
@Injectable()
class MyService {
private renderer: Renderer2;
constructor(rendererFactory: RendererFactory2) {
this.renderer = rendererFactory.createRenderer(null, null);
}
}
在此查看更多信息: https://github.com/angular/angular/issues/17824#issuecomment-351961146
See more on this here: https://github.com/angular/angular/issues/17824#issuecomment-351961146
以前的版本:
根据您的进口商品
import { Injectable, Renderer2 } from '@angular/core'
我怀疑您正在尝试在服务类中注入Renderer2
.它不会工作.您不能在服务中注入Renderer2
.它应适用于组件和组件内提供的服务.
i suspect that you're trying to inject Renderer2
in your service class. It won't work. You can't inject Renderer2
in service. It should work for components and services that are provided within component.
我们可以看一下源代码 https://github.com/angular/angular/blob/4.0.1/packages/core/src/view/provider.ts#L363-L373
We can take a look at 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;
}
它仅在元素注入器树内检查.而且没有其他地方可以提供此令牌
it checks only within element injector tree. And there are no other places when this token can be provided
因此,当您调用某些服务方法Renderer2从组件传递到服务"noreferrer"> https://github.com/angular/angular/issues/17824#issuecomment-311986129
So you have to pass Renderer2
from component to service when you're calling some service method https://github.com/angular/angular/issues/17824#issuecomment-311986129
或者您可以在组件内提供服务
or you can provide service within component
@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) {}
}
这篇关于在Angular 4中使用渲染器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!