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

时间:2018-05-08 10:52:37

标签: angular event-handling watch

我想分配一个角度服务的属性,结果来自 一个callaback功能 我有这个角度服务:

@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 ?
        }
    });
}

2 个答案:

答案 0 :(得分:1)

尝试使用lambda或“箭头函数”,它保留正文的this上下文。以下是关于何时使用以下内容的方便指南:When should I use Arrow functions in ECMAScript 6?

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

答案 1 :(得分:0)

请转换ES6功能 请阅读此link

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