无法在服务中使用渲染器? [英] Renderer cannot be used in Service?

查看:132
本文介绍了无法在服务中使用渲染器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Service中或仅在组件中使用Renderer?

Is it possible to use Renderer in Service or just in component?

如果我将渲染器注入服务,则会出现错误,表明缺少渲染器提供程序.

If I inject renderer into service I get error, that the Renderer provider is missing.

请参阅plunker的控制台:

See plunker's console:

import {Injectable, Component, Renderer, ElementRef} from 'angular2/core';

@Injectable()
class TestService {
  constructor(
    private _renderer: Renderer
    ) {}

  renderElement(elementRef: any) {
    this._renderer.createElement(elementRef.nativeElement, 'div');
  }
}

http://plnkr.co/edit/e8qlznCVbvZnXbLTk36z?p=preview

推荐答案

是的,就像Eric所说的那样,您可以将其从实际组件传递到Service,然后它将起作用.

Yea, like Eric said you can just pass it from the actual component to the Service and it will work.

但是,呈现对象的责任是组件而非服务的责任,服务是用来处理业务逻辑的(主要根据应用程序检索数据).

HOWEVER, the responsability to render an object is of the component, not the Service, services are meant to handle business logic (retrieve the data mostly, depending on your app).

整个想法是,如果您更改了演示文稿框架/库或任何与演示文稿有关的内容,则可以重用整个服务层,如果您执行类似的操作,则会将服务耦合到演示文稿,以后很难进行更改.

The whole idea is that you can reuse your whole services layer if you ever change your presentation framework/library or anything presentation related stuff at all, If you do things like that you'd be coupling your services to your presentation, making harder to make changes later on.

如果要在组件之间重用渲染逻辑,我将使用该逻辑创建一个父抽象类,并使用Component对其进行扩展,子组件将被注入渲染器,并使用<将其传递给父类. c0>应该调用父级构造函数的方法.

If you want to reuse the rendering logic between components, I'd create a parent abstract class with the logic and extend it with a Component, the children component would get injected the renderer and pass it to the parent class with the super() method that should call the parent's constructor.

至少可以像提出的解决方案一样创建一个@Injectable对象,但是将其命名为SomethingRenderer而不是Service,并将其与其余的实际数据服务分开.

At the very least you can make an @Injectable object like the proposed solution, but call it SomethingRenderer instead of Service and separate it from the rest of your real Data Services.

这篇关于无法在服务中使用渲染器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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