use a service inside a funcion

邮差的信 提交于 2020-07-10 07:00:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!