在服务中使用 $timeout:this.func 不是函数 [英] Using $timeout in service: this.func is not a function
问题描述
我一直在尝试使用 promise 在一定时间后结束用户会话.
问题是,每当从 $timeout 触发的函数中调用 service 中定义的函数时,该函数似乎是未定义的.我认为这是某种范围问题,但我无法自行解决此问题.
app.service('sessionService', function($timeout) {var closeSession = function() {this.resetUserInfo()//也许也可以做其他事情}this.start = function() {console.log("开始")承诺 = $timeout(closeSession, sessionLength)}this.resetUserInfo = function() {//重置会话}}
<块引用>
错误:this.resetUserInfo 不是函数
我尝试过的东西
- 不同的功能顺序
this.closeSession
而不是var
$timeout(function(){closeSession(this.resetUserInfo)}, sessionLength)
适当修改 closeSession
注意这个分配给那个.所以你使用的是服务的作用域,而不是方法的作用域.
app.service('sessionService', function($timeout) {var that = this;var closeSession = function() {that.resetUserInfo()//也许也可以做其他事情}this.start = function() {console.log("开始")承诺 = $timeout(closeSession, sessionLength)}this.resetUserInfo = function() {//重置会话}}
I've been trying to use promise to end user session after certain amount of time.
Problem is, whenever a function defined in service is called from the function triggered by $timeout, the function seems to be undefined. I think it's some kind of a scope issue, but I have not managed to fix this on my own.
app.service('sessionService', function($timeout) {
var closeSession = function() {
this.resetUserInfo()
// maybe do other things as well
}
this.start = function() {
console.log("start")
promise = $timeout(closeSession, sessionLength)
}
this.resetUserInfo = function() {
// reset session
}
}
Error: this.resetUserInfo is not a function
Things I have tried
- different ordering of functions
this.closeSession
instead ofvar
$timeout(function(){closeSession(this.resetUserInfo)}, sessionLength)
with proper modifications to closeSession
Note this assigned to that. So you are using the scope of the service instead of the scope of the method.
app.service('sessionService', function($timeout) {
var that = this;
var closeSession = function() {
that.resetUserInfo()
// maybe do other things as well
}
this.start = function() {
console.log("start")
promise = $timeout(closeSession, sessionLength)
}
this.resetUserInfo = function() {
// reset session
}
}
这篇关于在服务中使用 $timeout:this.func 不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!