0

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.

Quentin Laillé
  • 125
  • 1
  • 12
  • Not by itself, but you can inject the serve to the component and the component can pass itself to the service, but this shouldn't be necessary. Accessing the template should be done by the component. Just send commands from the service to the component about what it should do – Günter Zöchbauer Sep 01 '17 at 14:49

1 Answers1

0

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')
John
  • 17,163
  • 16
  • 65
  • 83
  • By following your solution, The problem is when do I call my component's method building the Chart when data from the service is available ? Can I use Event Emitter's or an @Input/@Output ? – Quentin Laillé Sep 01 '17 at 14:57
  • You can put an EventEmitter in one of the services that the services push data on to; your component can subscribe to that – John Sep 01 '17 at 15:18