2

我有一个 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?

4

1 回答 1

3

是的!请参阅angular $http 服务文档的这一部分。配置对象中的注释timeout字段。它确实,我认为,正是你所需要的。您可以解决此问题,然后请求将被标记为已取消,并且将调用错误处理程序。在错误处理程序中,您可以通过 http 状态代码过滤掉这种情况——它将等于 0。

这是演示这个的小提琴

于 2014-01-07T11:02:36.520 回答