我有以下课程:
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
};
}
我想要做的是在上面的$ interval函数中调用putTestQuestionResponses()。
我正在尝试做什么?有人能告诉我怎么做吗?
答案 0 :(得分:2)
在这种情况下,我们需要箭头功能,它将为我们保留上下文:
// 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);
有关详细信息,请参阅此处:
或在这里:
<{3}}