![](/img/trans.png)
[英]how can I access the variables of a service in the template of a component in angular
[英]Can a service get access to component's template
我有兩個彼此通信的服務(A和B),當另一個接收異步數據(這些數據在其他地方使用,因此B是獨立的)時,A必須構建一個圖表。 我試圖將對組件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
}
}
問題不在於數據,而是當在組件A中使用此方法時使圖表起作用,我只是想了解為什么我不能使用相同的過程從模板中獲取元素。
我認為您需要進行以下更改:
在HTML中:
<canvas #historicChart></canvas>
在組件中:
@ViewChild('historicChart') historicChart: ElementRef;
然后,在獲得組件中的數據之后:
const ctx = (this.historicChart.nativeElement as HTMLCanvasElement).getContext('2d')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.