如何从实例调用的回调函数中设置实例属性?

How to set instance property from a callback function invoked by the instance?

我想分配一个 angular 服务的属性,结果来自 回调函数 我有这个 angular 服务:

@Injectable()
export class SkillsManagerService {

    private skill: any;
    private event: any;
    constructor() {
        // i have an event instance
        event = getEvent ();
        this.startWatching();
    }

    //function that start watching the event
    function startWatching() {
        event.watch(function(err, res) {
            // how to assign this.skill = res ?
        }
    });
}

尝试使用 lambda 或 "arrow function",它会保留正文的 this 上下文。这是关于何时使用什么的便捷指南:我什么时候应该在 ECMAScript 6 中使用箭头函数?

function startWatching() {
    event.watch((err, res) => {
      this.skill = res;
    });
  }

请转换ES6函数 请阅读此 link

 pulic function startWatching() {
     event.watch((err, res) => {
     this.skill = res 
   }
  });