多久角度诺言生活? [英] How long does an angular promise live?

查看:126
本文介绍了多久角度诺言生活?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解的角度服务和组件的生命周期。

I'm trying to understand the life cycle of angular services and components.

说我有一个使用HTTP服务的控制器:

Say I have a controller that uses an http service:

function MyController($scope, $http) {
  $http.get('/service').success(function(data) {
    // handle the response
  });
}

的事情是,该控制器可被连接到一个图。我想,以确保响应被丢弃如果视图已被删除,这是与其他请求大公可以在应用程序的其他部分被触发prevent冲突。将控制器的实例被销毁,有了它,如果视图被删除未决从 $ HTTP 服务被取消电话?例如,当用户导航离开(无需重新加载)从页面造成一个JavaScript渲染新的一节?

The thing is that this controller may be attached to a view. And I want to make sure that the response is discarded if the view has been removed, this is to prevent conflicts with other requests thay may be triggered in other parts of the application. Will the instance of the controller be destroyed and with it, pending calls from the $http service be canceled if the view is removed? For example, when the user navigates away (without reloading) from the page causing a Javascript render of a new section?

[修改]我创建了一个的jsfiddle 这表明,在至少在$超时服务,挂起的操作仍然是 $范围后运行通过导航走销毁。有没有一种简单的方法来异步操作连接到范围,使他们将被自动销毁?

[Edit] I created a jsfiddle that shows that, at least for the $timeout service, the pending operations are still running after the $scope is destroyed by navigating away. Is there a simple way to attach async operations to the scope so that they will be destroyed automatically?

推荐答案

首先,将你的诺言的引用,然后传递参照取消功能。这解决了一个拒绝的承诺。所以,你也可以只使用 promise.reject()的取消(承诺)

First, attach a reference to your promise, then pass that reference to the cancel function. This resolves the promise with a rejections. So you could also just use promise.reject() in place of cancel(promise)

function MyController($scope, $http) {
  var promise =  $http.get('/service');

  promise.success(function(data){

  });

   $scope.$on(
         "$destroy",
         function() {
            promise.reject("scope destroyed, promise no longer available");
         }
   );
}

这篇关于多久角度诺言生活?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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