[英]How to get multiple $http when Consume Restful APIs with angularjs
I try to get from JSONPlaceholder data to display, and I need more than one $http.get
, this is my code. 我尝试从JSONPlaceholder数据获取显示,并且我需要多个$http.get
,这是我的代码。 The problem is, that from the second call I don't get any data 问题是,从第二次通话开始,我没有任何数据
MyAlbum1.controller('albumList', function($scope, $http) {
$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;
});
});
If I try for example to display in the partial view albumUsers.name
it will not display. 例如,如果我尝试显示在部分视图albumUsers.name
,它将不会显示。 Only if I put first the $http.get('http://jsonplaceholder.typicode.com/users').
仅当我首先放置$http.get('http://jsonplaceholder.typicode.com/users').
but then it will not display the albumDetails.id
但是它将不会显示albumDetails.id
So how do I get more than one http.get
? 那么,如何获得多个http.get
?
Thanks 谢谢
You could load 1 after another: 您可以一个接一个地加载:
MyAlbum1.controller('albumList', function($scope, $http) {
$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;
});
});
});
or 要么
MyAlbum1.controller('albumList', function($scope, $http, $q) {
$q.all([$http.get('http://jsonplaceholder.typicode.com/albums'), $http.get('http://jsonplaceholder.typicode.com/users')]).then(function(response) {
});
});
use $q
to send multiple requests at once.first inject the $q
to controller. 使用$q
发送多个请求。首先将$q
注入控制器。
MyAlbum1.controller('albumList', function($scope, $http,$q) {
$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;
})
})
Thanks! 谢谢! Work now. 在工作,在忙。 Here's the code I'm using: 这是我正在使用的代码:
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;
});
}); });
But, when call the data, I need to do as follow: 但是,在调用数据时,我需要执行以下操作:
User: {{albumUsers[1].name}}
Like, I need the [1] in order that it will work. 就像,我需要[1]才能起作用。 Thanks 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.