服务能否访问组件的模板
Can a service get access to component's template
我有两个服务(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 中使用此方法时使图表工作,我只是想了解为什么我不能使用相同的过程从我的模板中获取元素。
我认为您需要进行以下更改:
- 您的服务应该只负责获取数据并将其返回给您的组件
- 在您的组件中,您不应直接引用文档。如果您确实需要引用该元素,您可能希望这样做:
在HTML中:
<canvas #historicChart></canvas>
在组件中:
@ViewChild('historicChart') historicChart: ElementRef;
那么在你获取组件中的数据之后:
const ctx = (this.historicChart.nativeElement as HTMLCanvasElement).getContext('2d')
我有两个服务(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 中使用此方法时使图表工作,我只是想了解为什么我不能使用相同的过程从我的模板中获取元素。
我认为您需要进行以下更改:
- 您的服务应该只负责获取数据并将其返回给您的组件
- 在您的组件中,您不应直接引用文档。如果您确实需要引用该元素,您可能希望这样做:
在HTML中:
<canvas #historicChart></canvas>
在组件中:
@ViewChild('historicChart') historicChart: ElementRef;
那么在你获取组件中的数据之后:
const ctx = (this.historicChart.nativeElement as HTMLCanvasElement).getContext('2d')