我目前正在学习AngularJS,但无法将一段代码从示例转换为自己的代码。
在来自Urish的以下示例中,我了解到变量promise必须包含函数和其余函数执行所必需的查询。
var promise = asyncFunction(parameters);
promise.then(
function (result) {
// Do Something with the result
},
function (error) {
// Handle error (exception, etc).
});
因此,在我的情况下,如果我想首先进行两个$ http查询,并使用接收到的数据填充第三个查询的url,是否会是这样?
var promise = $scope.getDetails(id);
$scope.getDetails = function (id) {
$http.get('http://api.discogs.com/artists/' + id).
success(function(data) {
$scope.artist = data;
});
$http.get('http://api.discogs.com/artists/' + id + '/releases?page=1&per_page=100').
success(function(data2) {
$scope.releases = data2.releases;
});
$scope.clicked = true;
$scope.sliding = true;
}
promise.then(
$scope.getImages = function (title, name) {
$http.get('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=e8aefa857fc74255570c1ee62b01cdba&artist=' + name + '&album='+ title +'&format=json').
success(function(data4) {
$scope.images = data4;
});
},
function (error) {
// Handle error (exception, etc).
});
这是正确的方法吗?我想念什么吗?
编辑:我用本杰明解决方案创建了一个working Plunker,但是AngularJS刹车了。知道问题可能在哪里吗?
最佳答案
为了结合诺言,就像Florian建议的那样,您应该使用.all
:
$scope.getDetails = function (id) {
var api = 'http://api.discogs.com/artists/';
return $q.all([$http.get(api + id),
$http.get(api + id + '/releases?page=1&per_page=100')]);
});
然后用法是:
$scope.getDetails(YOURID).then(function(results){
$scope.artist = results[0];
$scope.releases = results[1].releases;
});
或在三个查询示例中:
$scope.getDetails(YOURID).then(function(results){
$scope.artist = results[0];
$scope.releases = results[1].releases;
// data for getImages available here
return $http.get('http://ws.audioscrobbler.com/2.0/?...' + results[0]...
});
(此外,我会将其投入服务)