简体   繁体   English

angularjs服务函数调用自身

[英]angularjs service function invoke itself

I want to create a startService function in angularjs service (factory). 我想在angularjs服务(工厂)中创建一个startService函数。 I want to startService function check if it can start service and if not it will invoke itself with a timeout and than checks again. 我想要startService函数检查它是否可以启动服务,如果不能,它将以超时调用自身,然后再次检查。

startService: function() {      
      if(!someComaprison) {
        $timeout(this.startService, 5000);
        return;
      }

      //starts service
    },

But in the next start of the function it crashes because this is undefined. 但是在函数的下一次启动时,它会崩溃,因为这是未定义的。 How to make such a loop in services? 如何在服务中形成这样的循环? I have no problem doing it with controllers functions? 我可以通过控制器功能做到这一点吗?

You need to pass context (in this case-> this ) too. 您还需要传递上下文 (在这种情况下 -> this )。 Try like this: 尝试这样:

$timeout(this.startService.bind(this), 5000);

in order to keep the right this context,you need to bind the function to this 为了保持正确的this背景下,你需要的功能绑定到这个

$timeout(this.startService.bind(this), 5000);

or the function executed in the timeout will not know what this refers to. 否则在超时中执行的函数将不知道this是指什么。

have a look a the following article : 看一下下面的文章:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this

EDIT : for the other issue : 编辑:对于另一个问题:

var that = this;

this.startHttpRequest = function(userId) {
    var httpRequest = $http.post(somedata....);


    httpRequest.success(function(data){
      that.startHttpRequest(data.userId);
    });
  }

But, dont ask 2 different questions like that, or edit your first question instead of posting a question as an answer. 但是,不要这样问两个不同的问题,也不要编辑您的第一个问题,而不要发布问题作为答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM