【问题标题】:AngularJS $destroy on $rootscope never gets called to cancel timeouts$rootscope 上的 AngularJS $destroy 永远不会被调用来取消超时
【发布时间】:2017-10-15 14:18:37
【问题描述】:

我有以下代码-

function initialize() {
  var defer = $q.defer();
  var deferTimer = $q.defer();

  var cancelTimeout = $timeout(function() {
    if (defer !== null) {
      ctrlr.setProcessingParameters('XXX');
      defer = ctrlr.openProgressBar();
      deferTimer.resolve();
    }
  }, 1000);

  deferTimer.promise.then(function() {
    var cancelTimeout2 = $timeout(function() {
      if (defer !== null) {
        defer.resolve();
        ctrlr.setProcessingParameters('Please Wait...');
        defer = ctrlr.openProgressBar();
      }
    }, 4000);
  });

  //Process Backend service n resolbve defer....

}

// cancel the $timeout service
$rootScope.$on('$destroy', function() {
  logger.log("cancelTimeout..timer..");
  if (cancelTimeout) {
    $timeout.cancel(cancelTimeoutProcess);
    cancelTimeout = null;
  }
});

// cancel the $timeout service
$rootScope.$on('$destroy', function() {
  logger.log("cancelTimeout2..timer..")
  if (cancelTimeout2) {
    $timeout.cancel(cancelTimeout2);
    cancelTimeout2 = null;
  }
});

我没有看到记录器打印或调试器进入$destroy。不知道这里发生了什么。

【问题讨论】:

  • 我不知道为什么它没有进入$rootScope.$on('$destroy' 函数,但cancelTimeoutcancelTimeout2 肯定会抛出一个错误,因为它们的范围是initialize 函数?
  • @George 如果我将其添加为全局变量,那应该可以解决问题吗?我听说我们不应该在任何 fn 中使用取消计时器逻辑。
  • $rootScope 在您关闭或离开页面时被销毁。一切都会过去的,所以没有什么可以清理的......
  • @tanmay 那么我该如何取消/终止这些超时?
  • @Smitha 你无权访问$scope

标签: javascript angularjs timeout destroy


【解决方案1】:

$rootScope 在您关闭或离开页面时被销毁。那时一切都会消失,所以那时没有什么可以清理的。

您正在寻找的是 $destroy 而不是 $scope

$scope.$on('$destroy', function() {
  logger.log("cancelTimeout..timer..");
  if (cancelTimeout) {
    $timeout.cancel(cancelTimeoutProcess);
    cancelTimeout = null;
  }
});

在控制器中,$scope.$on('$destroy'.. 将在与当前$scope 关联的控制器被销毁(而不是整个应用程序)时被调用。

【讨论】:

    猜你喜欢
    • 2019-04-21
    • 1970-01-01
    • 2012-10-27
    • 2013-10-12
    • 2012-03-27
    • 2013-08-29
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多