简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM