Angular $ http服务,如何取消/取消订阅待处理的请求?

时间:2014-01-07 10:43:46

标签: javascript angularjs angular-http

我有一个执行的AngularJS应用程序 - 1个获取主用户配置文件的请求,其中包含对用户朋友的引用, - 然后每个朋友请求1个请求检索朋友个人资料。

当我们点击朋友的个人资料时,我们会将此个人资料加载为主要个人资料。

我在RDF /语义网络世界中,所以我不能以不同的方式对这些交互进行建模,这不是问题的关键。

这是我正在尝试构建的应用程序的早期版本,可以帮助您了解我的问题:http://sebastien.lorber.free.fr/addressbook/app/


代码如下:

$scope.currentProfileUri = 'http://bblfish.net/people/henry/card#me';

$scope.$watch('currentProfileUri', function() {
  console.debug("Change current profile uri called with " + $scope.currentProfileUri);
  loadFullProfile($scope.currentProfileUri);
})

// called when we click on a user's friend
$scope.changeCurrentProfileUri = function changeCurrentProfileUri(uri) {
  $scope.currentProfileUri = uri;
}

function loadFullProfile(subject) {
  $scope.personPg = undefined;
  // we don't want to capture the scope variable in the closure because there may be concurrency issues is multiple calls to loadFullProfile are done
  var friendsPgArray = [];
  $scope.friendPgs = friendsPgArray;
  fetchPerson(subject).then(function(personPg) {
    $scope.personPg = personPg
    fetchFriends(personPg,function onFriendFound(relationshipPg) {
      friendsPgArray.push(relationshipPg);
    });
  },function(error) {
    console.error("Can't retrieve full profile at "+uri+" because of: "+error);
  });
}

因此,当http响应在promise中可用时,朋友会在他们到来时附加到UI。

问题是函数changeCurrentProfileUri可以被多次调用,并且有可能在有待加载当前用户的朋友的待处理请求时调用它。

我想知道的是,在changeCurrentProfileUri来电时,是否可以取消之前尚待处理的http请求?因为我正在尝试加载另一个用户配置文件,所以我不再需要它们了。 这些待处理的请求将填充不再包含在范围内的friendsPgArray实例,并且不会放在范围内,因此它无用。


使用Java Futures或RxScala或RxJava等框架,我发现通常会有某种“取消”或“取消订阅”方法,可以取消对未来结果的兴趣。用Javascript做这样的事情有可能吗?和AngularJS?

1 个答案:

答案 0 :(得分:3)

是的,它是!请参阅角度$ http服务文档的this section。注意config对象中的timeout字段。我认为,它确实符合您的需求。您可以解决此pormise,然后将请求标记为已取消,并将调用错误处理程序。在错误处理程序中,您可以通过http状态代码过滤掉这种情况 - 它将等于0。

以下fiddle证明了这一点

相关问题