简体   繁体   中英

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). 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 :

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

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:

 <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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM