繁体   English   中英

Angular $ http服务,如何取消/取消订阅未决请求?

[英]Angular $http service, how to cancel / unsubscribe pending requests?

我有一个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);
  });
}

因此,当promise中提供http响应时,朋友会随他们来到时附加到UI。

问题在于,函数changeCurrentProfileUri可以被多次调用,并且有可能在尚有待加载当前用户的朋友的未决请求时被调用。

我想知道的是,是否有可能在changeCurrentProfileUri调用上取消以前仍在等待处理的http请求? 因为我正试图加载另一个用户配置文件,所以不再需要它们了。 这些待处理的请求将填充不在该范围内的friendsPgArray实例,并且不会放入该范围内,因此它是无用的。


使用Java Futures或RxScala或RxJava之类的框架,我已经看到通常存在某种“取消”或“取消订阅”方法,该方法允许注销对未来结果的兴趣。 用Javascript可以做这样的事情吗? 和AngularJS一起使用?

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

这是小提琴来证明这一点

暂无
暂无

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

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