在服务中使用$超时:this.func不是一个函数 [英] Using $timeout in service: this.func is not a function

查看:191
本文介绍了在服务中使用$超时:this.func不是一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图用承诺一定的时间后结束用户会话。<​​/ P>

问题是,每当服务定义的函数是由$超时触发函数调用,功能似乎是不确定的。我认为这是某种范围的问题,但我还没有设法解决这个问题对我自己的。

  app.service('sessionService',函数($超时){
    VAR closeSession =功能(){
        this.resetUserInfo()
        //也许做其他事情,以及
    }    this.start =功能(){
         的console.log(开始)
         诺= $超时(closeSession,sessionLength)
    }    this.resetUserInfo =功能(){
        //复位会话
    }
}


  

错误:this.resetUserInfo不是一个函数


事情我都试过


  • 不同的排序功能

  • this.closeSession 而不是 VAR

  • $超时(函数(){closeSession(this.resetUserInfo)},sessionLength)适当修改closeSession


解决方案

请注意这个分配给。所以,你正在使用的服务,而不是方法的范围的范围。

  app.service('sessionService',函数($超时){
    VAR认为这=;
    VAR closeSession =功能(){
        that.resetUserInfo()
        //也许做其他事情,以及
    }    this.start =功能(){
         的console.log(开始)
         诺= $超时(closeSession,sessionLength)
    }    this.resetUserInfo =功能(){
        //复位会话
    }
}

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

解决方案

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

这篇关于在服务中使用$超时:this.func不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆