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

人盡茶涼 提交于 2019-12-23 04:48:32

问题


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 of var
  • $timeout(function(){closeSession(this.resetUserInfo)}, sessionLength) with proper modifications to closeSession

回答1:


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



回答2:


An alternative would be to make resetUserInfo a local function and then attach to it this later on. For example:

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;

}



来源:https://stackoverflow.com/questions/34064666/using-timeout-in-service-this-func-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!