So following my last question of how to consume multiple $http, I need also to sort the data and match them. It's mean, I have the Albums, Photos and users:
http://jsonplaceholder.typicode.com/albums
http://jsonplaceholder.typicode.com/photos
http://jsonplaceholder.typicode.com/users
For each Album I need to display the owner name and number of photos. So I try this to get the Album by Id, but it gives me error:
$http.get('http://jsonplaceholder.typicode.com/albums/'+ $scope.id + '/photos')
Or I also try this:
$http.get('http://jsonplaceholder.typicode.com/albums/'+ albumUsers.id + '/photos')
But still get error.
The question is if there's a way to link / create dependency between them, so the second controller basically rely on the first one? Thanks
So this is the controller to get the albums and the users
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;
});
});
And this the controller to get each album - for the example, I'm using a link to one specific album:
MyAlbum.controller('photoList', function($scope, $http) {
$http.get('http://jsonplaceholder.typicode.com/albums/1/photos')
.then(function(response) {
$scope.PhotoDetails = response.data;
});
});
The thing is that instead of albums/1 it should be albums/id
You can chained the $http
calls together.Success function of the first $http
request calls the second $http
request.
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.