0

I want to assign an attribute of an angular service with result comes from a callaback function I have this angular service:

@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 ?
        }
    });
}
Maximilian Riegler
  • 22,720
  • 4
  • 62
  • 71
maroodb
  • 1,026
  • 2
  • 16
  • 28
  • 1
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Jota.Toledo May 08 '18 at 10:58
  • 1
    this isnt an issue related to angular IMO, is related to the language – Jota.Toledo May 08 '18 at 10:59

2 Answers2

1

Try using a lambda or "arrow function", which preserves the this context for the body. Here is a handy guide on when to use what: When should I use Arrow functions in ECMAScript 6?

function startWatching() {
    event.watch((err, res) => {
      this.skill = res;
    });
  }
Maximilian Riegler
  • 22,720
  • 4
  • 62
  • 71
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
0

Please convert ES6 function please read this link

 pulic function startWatching() {
     event.watch((err, res) => {
     this.skill = res 
   }
  });
Sharma Vikram
  • 2,440
  • 6
  • 23
  • 46