user2678324
user2678324

Reputation:

How to call a function inside constructor

I have the following class:

class QuestionService {
   static $inject = [
      "$interval",
      "$http",
      "$state"
   ];
   constructor(
      private $interval,
      private $http: ng.IHttpService,
      private $state
   ) {

      $interval(function () {
         this.putTestQuestionResponses()  // <-- error here 
                                          // this.putTestQuestionResponse
                                          // is not a function
      }, 5 * 1000);
   }

   putTestQuestionResponses = () => {
      // do something
   };
}

What I wanted to do is call the putTestQuestionResponses() inside the $interval function above.

Is what I'm trying to do possible? Can someone let me know how to do this?

Upvotes: 2

Views: 292

Answers (1)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123861

In this case, we need arrow function, which will keep the context for us:

// instead of this
//$interval(function () { // this will be ... not expected
// we need arrow function
$interval(() => {         // arrow functions keep 'this' related to local context
     this.putTestQuestionResponses() 
}, 5 * 1000);

see this for more info:

TypeScript Arrow Function Tutorial

or here:

Arrow Functions by Basarat

Upvotes: 2

Related Questions