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 ?
        }
    });
}
rinukkusu
  • 20,045
  • 4
  • 57
  • 66
maroodb
  • 848
  • 9
  • 24
  • 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;
    });
  }
rinukkusu
  • 20,045
  • 4
  • 57
  • 66
Pardeep Jain
  • 71,130
  • 29
  • 141
  • 199
0

Please convert ES6 function please read this link

 pulic function startWatching() {
     event.watch((err, res) => {
     this.skill = res 
   }
  });
Sharma Vikram
  • 2,172
  • 4
  • 19
  • 41