服务是否可以访问组件的模板

时间:2017-09-01 14:32:27

标签: angular typescript chart.js angular2-template angular-services

我有两个服务(A和B)在彼此之间进行通信,A必须在另一个接收异步数据时构建图表(这些数据在其他地方使用,因此B是独立的)。我试图将我对组件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 个答案:

答案 0 :(得分:0)

我认为您需要进行以下更改:

  1. 您的服务应仅负责获取数据并将其返回到您的组件
  2. 在您的组件中,您不应该直接引用该文档。如果你真的需要引用这个元素,你可能想要这样做:
  3. 在HTML中:

     <canvas #historicChart></canvas>
    

    在组件中:

    @ViewChild('historicChart') historicChart: ElementRef;
    

    然后,您获得了组件中的数据:

    const ctx = (this.historicChart.nativeElement as HTMLCanvasElement).getContext('2d')
    
相关问题