[英]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: 我认为您需要进行以下更改:
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.