如何从委派函数访问服务变量(回调)

时间:2017-07-30 17:53:26

标签: javascript angularjs callback angularjs-service

我正在使用一个服务来获取需要由服务更新的变量。但是我无法在anonymus函数/委托函数中找到var。

(function() {
  'use strict';

  angular
      .module('yoTest')
      .service('mainService', mainService);

  /** @ngInject */
  function mainService($timeout) {
    this.counter = 1;
    this.updateCounter = function updateCounter() {
      this.counter++;
      $timeout(updateCounter, 500);
    }
    this.updateCounter();
  }
})();

如果我通过$timeout重新加载“updateCounter”,我会收到错误,为什么?

如何通过超时和委托/回调来访问它?

2 个答案:

答案 0 :(得分:2)

问题是在调用函数时你刚刚在updateCounter回调中传递了$timeout函数引用。因为当$timeout尝试评估该功能时,this属于updateCounter将属于this,而不是考虑this mainService 。在这种情况下,您必须使用.bind(this)

显式传递当前上下文
this.updateCounter = function updateCounter() {
  this.counter++;
  console.log(this.counter)
  $timeout(updateCounter.bind(this), 500);
}

PLuker

使用Fat Arrow函数

可以在ES6中实现同样的功能
$timeout(() => { updateCounter () }, 500);

答案 1 :(得分:2)

作为Pankaj的答案的替代方法,您可以将当前上下文绑定到变量,并使用此变量引用属性和函数。

function mainService($timeout) {
  var service = this;

  this.counter = 1;

  this.updateCounter = function updateCounter() {
    service.counter++;
    console.log(service.counter)
    $timeout(service.updateCounter, 500);
  }

  this.updateCounter();

}

http://plnkr.co/edit/EuTiiP8HZUPulmJIX3IP