问题
I'm using highcharts and angular.
At this moment I want to use translateService inside the point formatter function:
constructor(private translateService: TranslateService) {
}
private getOptions() {
return {
name: this.name,
color: this.color,
tooltip: {
pointFormatter: function () {
/* this line is my problem, how to use this.translateService here! */
const myTranslation = translateService.instant('KEY', {value:this.y});
return `<span>\u25CF</span> ${myTranslation}`;
}
},
};
}
回答1:
You can use IIFE to store this from the outer scope:
tooltip: {
pointFormatter: (function(component) {
return function() {
console.log(this, component);
}
})(this)
}
Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4918/
回答2:
Using function() { } syntax will scope this to the function itself. To scope this to the outer scope - to be able to interact with the service declared outside of the function - use an arrow function and call this.translateService.
constructor(private translateService: TranslateService) {
}
private getOptions() {
return {
name: this.name,
color: this.color,
tooltip: {
pointFormatter: () => {
const myTranslation = this.translateService.instant('KEY', {value:this.y});
return `<span>\u25CF</span> ${myTranslation}`;
}
},
};
}
You are already using this inside the function, so there's a chance that you will have to investigate another way of getting this.y. Maybe it's passed in as an arg, or maybe it's declare outside and you just chosen to omit it from the question as unecessary detail?
来源:https://stackoverflow.com/questions/60718272/use-a-service-inside-a-funcion