在服务中使用 $timeout:this.func 不是函数

Using $timeout in service: this.func is not a function

我一直在尝试在一定时间后使用 promise 结束用户会话。

问题是,每当从 $timeout 触发的函数调用服务中定义的函数时,该函数似乎未定义。我认为这是某种范围问题,但我还没有设法自行解决这个问题。

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

我尝试过的东西

注意这个分配给那个。因此,您使用的是服务范围而不是方法范围。

 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
    }
} 

另一种方法是使 resetUserInfo 成为本地函数,然后稍后附加到它。例如:

app.service('sessionService', function($timeout) {

    //private definition
    var resetUserInfo = function() {

    }

    var closeSession = function() {
        resetUserInfo(); //call the private version
    }

    this.start = function() {
         console.log("start")
         promise = $timeout(closeSession, sessionLength)
    }

    //now expose method as public here
    this.resetUserInfo = resetUserInfo;

}