当使用angularjs使用Restume API时,如何使用多个$ http对数据进行排序和匹配

时间:2017-05-16 17:47:03

标签: angularjs json rest

因此,关于如何使用多个$ 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')

但仍然会出错。

问题是,是否有一种方法可以链接/创建它们之间的依赖关系,所以第二个控制器基本上依赖于第一个控制器? 感谢

2 个答案:

答案 0 :(得分:0)

所以这是获取相册和用户的控制器

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

答案 1 :(得分:0)

您可以将$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();
相关问题