![](/img/trans.png)
[英]How to get multiple $http when Consume Restful APIs with angularjs
[英]How to sort and match data with multiple $http when Consume Restful APIs with angularjs
因此,在最后一個關於如何使用多個$ http的問題之后,我還需要對數據進行排序和匹配。 意思是,我有相冊,照片和用戶:
http://jsonplaceholder.typicode.com/albums
http://jsonplaceholder.typicode.com/photos
http://jsonplaceholder.typicode.com/users
對於每個相冊,我需要顯示所有者名稱和照片數量。 因此,我嘗試通過ID獲得相冊,但這給了我錯誤:
$http.get('http://jsonplaceholder.typicode.com/albums/'+ $scope.id + '/photos')
或者我也嘗試這樣:
$http.get('http://jsonplaceholder.typicode.com/albums/'+ albumUsers.id + '/photos')
但是仍然會出錯。
問題是它們之間是否存在鏈接/創建依賴關系的方法,因此第二個控制器基本上依賴第一個控制器? 謝謝
這是獲取專輯和用戶的控制器
MyAlbum.controller('albumList', function($scope, $http, $q) {
$http.get('http://jsonplaceholder.typicode.com/albums').
then(function(response) {
$scope.albumDetails = response.data;
});
$http.get('http://jsonplaceholder.typicode.com/users').
then(function(response) {
$scope.albumUsers = response.data;
});
$q.all(['http://jsonplaceholder.typicode.com/albums','http://jsonplaceholder.typicode.com/users',]).
then(function(response){
$scope.albumDetails = response[0].data;
$scope.albumUsers= response[1].data;
});
});
這是獲取每張專輯的控制器-例如,我正在使用一個特定專輯的鏈接:
MyAlbum.controller('photoList', function($scope, $http) {
$http.get('http://jsonplaceholder.typicode.com/albums/1/photos')
.then(function(response) {
$scope.PhotoDetails = response.data;
});
});
事實是,應該不是相冊/ 1,而應該是相冊/ id
您可以將$http
調用鏈接在一起,第一個$http
請求的成功函數將調用第二個$http
請求。
function firstCall() { // It will return a promise.
return $http({
method: 'GET',
url: firstAPIURL
});
}
function dependantCall() { // It will return a promise
return $http({
method: 'GET',
url: secondAPIURL
});
}
$scope.onloadRequest = function() { // This function will execute on load the view/controller.
firstCall()
.then(function(result) {
$scope.value = result.data; // Now that the server has answered, you can assign the value to $scope.value, and then, call the second function.
dependantCall().then(function(dependentResult) {
// Your code comes here
}, function(dependentError){
// If an error happened during the dependent call, handle it here.
});
}, function(error){
// If an error happened during first call, handle it here.
});
};
$scope.onloadRequest();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.