[英]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.我想要做的是在上面的 $interval 函数中调用 putTestQuestionResponses() 。
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:请参阅此了解更多信息:
or here:或在这里:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.