2

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.