簡體   English   中英

服務可以訪問組件的模板嗎

[英]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中使用此方法時使圖表起作用,我只是想了解為什么我不能使用相同的過程從模板中獲取元素。

我認為您需要進行以下更改:

  1. 您的服務應僅負責獲取數據並將其返回給組件
  2. 在組件中,您不應直接引用文檔。 如果您確實需要引用該元素,則可能需要這樣做:

在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM