简体   繁体   English

服务可以访问组件的模板吗

[英]Can a service get access to component's template

I have two service (A and B) communicating between each others, A has to build a chart when the other one received asynchronous datas (those datas are used somewhere else, so B is independant). 我有两个彼此通信的服务(A和B),当另一个接收异步数据(这些数据在其他地方使用,因此B是独立的)时,A必须构建一个图表。 I've tried to shift what I do with the component A into its service but it looks like I cant get access to the template of the component : 我试图将对组件A的操作转移到其服务中,但是看起来我无法访问该组件的模板:

@Injectable()
export class HistoricGraphService {

... // doing stuff

  onNewData() {
    const canvas = <HTMLCanvasElement>document.getElementById('historic-chart');
    const ctx = canvas.getContext('2d');
    ... building the chart based on datas, timestamp and much more
  }
}

The problem isnt around the datas, making the chart works when this method is used in Component A, I'd just like to understand why I cant use that same process to get an Element from my template. 问题不在于数据,而是当在组件A中使用此方法时使图表起作用,我只是想了解为什么我不能使用相同的过程从模板中获取元素。

I think you'd need to make the following changes: 我认为您需要进行以下更改:

  1. Your service should only be responsible for getting the data and returning it to your component 您的服务应仅负责获取数据并将其返回给组件
  2. In your component, you shouldn't directly reference the document. 在组件中,您不应直接引用文档。 If you truly need to reference the element, you'd probably want to go about doing it like so: 如果您确实需要引用该元素,则可能需要这样做:

In the HTML: 在HTML中:

 <canvas #historicChart></canvas>

In the Component: 在组件中:

@ViewChild('historicChart') historicChart: ElementRef;

Then after you've gotten the data in the component: 然后,在获得组件中的数据之后:

const ctx = (this.historicChart.nativeElement as HTMLCanvasElement).getContext('2d')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 angular 组件的模板中访问服务的变量 - how can I access the variables of a service in the template of a component in angular angular2指令可以访问要应用到的组件的模板吗? - Can an angular2 directive access the template of a component it's applied to? 如何访问或检查超级父级组件中子组件的模板驱动表单的验证 - How can I access or check validation of the child component's template driven form in the super parent's component 无法访问组件中现有服务的属性 - Can't access property of existing service in component 我怎样才能访问组件代码的模板生成的局部变量? - How can I get access to a template generated local variable to component code? 在组件的模板中使用服务数据-这是一种好习惯吗? - Using service data in component's template - is it a good practice? 我们可以在子组件中访问由父组件更改的服务数据吗 - Can we access service data changed by parent component in child component 有没有办法限制对组件及其模板的方法/变量访问? - Is there a way to restrict method/variable access to the component and it's template? 无法为组件获取数据角度服务 - can't get data angular service to component Angular2组件无法访问模板内的类属性 - Angular2 Component can't access class property inside template
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM