簡體   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