Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何取消/取消订阅挂起的请求?_Javascript_Angularjs_Angular Http - Fatal编程技术网

Javascript 如何取消/取消订阅挂起的请求?

Javascript 如何取消/取消订阅挂起的请求?,javascript,angularjs,angular-http,Javascript,Angularjs,Angular Http,我有一个AngularJS应用程序,它执行 -1请求获取主用户配置文件,其中包含对用户朋友的引用, -然后每个朋友请求一个请求来检索朋友配置文件 当我们点击朋友的个人资料时,我们会将此个人资料作为主个人资料加载 我身处RDF/语义web世界,因此我无法对这些交互进行不同的建模,这不是问题的重点 这是我尝试构建的应用程序的早期版本,可以帮助您了解我的问题: 代码如下所示: $scope.currentProfileUri = 'http://bblfish.net/people/henry/ca

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

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

我身处RDF/语义web世界,因此我无法对这些交互进行不同的建模,这不是问题的重点

这是我尝试构建的应用程序的早期版本,可以帮助您了解我的问题:


代码如下所示:

$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
字段。我想这正是你所需要的。您可以解决此问题,然后将请求标记为已取消,并调用on error处理程序。在错误处理程序中,您可以通过http状态代码过滤掉这种情况-它将等于0


这里演示一下这一点。我不想设置全局请求超时,但希望能够基于用户交互取消挂起的请求。我不知道超时能为我做什么。这不是全局超时(至少不是唯一的)。它只是字段的名称(不是很好的名称)。事实上-这是一个承诺,可能是由$q服务创建的,并根据用户交互来解决(取消请求)。@SebastienRobber为您添加了fiddle。这意味着我的
fetchFriends
应该返回一个承诺列表,可以解决取消http请求的问题?@SebastienRobber是的,这是一个可能的解决方案。