如何在Angular中链接多个HTTP调用 [英] How to chain multiple http calls in Angular
本文介绍了如何在Angular中链接多个HTTP调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用多个外部数据库来获取在数据库中创建所需记录所需的数据.我有一个应用程序,用户可以在其中搜索电影并将其添加到监视列表.
I use several external database sto get the data I need to create the record I want in my database. I have an application where users can search and add a movie to their watchlist.
为此,我需要以下数据,
For this I need the following data,
- 电影数据,例如标题,发行日期和ID.
- imdb评级.
- 电影学分,例如演员和导演.
这就是我现在的做法,
movieAdd.add(movie.id).then(function(response){
$scope.movieListID = response;
movieAdd.imdbRating($scope.movieListID.imdb_id).then(function(response){
$scope.movieImdbRating = response;
movieAdd.crew(movie.id).then(function(response){
$scope.movieCredits = response
return createMovie.create({
id: $scope.movieListID.id,
imdb_rating: $scope.movieImdbRating.imdbRating,
title: $scope.movieListID.original_title,
image: $scope.movieListID.poster_path,
movie_id: $scope.movieListID.id,
backdrop: $scope.movieListID.backdrop_path,
overview: $scope.movieCredits.overview
})
})
})
})
我调用服务,将响应返回到存储区中,以便以后使用,依此类推.
I call a service, return the store the response in a scope so I can use it later on, and so on.
这是这样做的正确方法,还是有更好的方法?
Is this the correct way of doing this, or is there a better way?
推荐答案
当链接诺言时,您可以只返回诺言而不是嵌套它们,就像这样:
movieAdd.add(movie.id).then(function(response){
$scope.movieListID = response;
return movieAdd.imdbRating($scope.movieListID.imdb_id);
}).then(function(response){
$scope.movieImdbRating = response;
return movieAdd.crew(movie.id)
}).then(function(response){
$scope.movieCredits = response
return createMovie.create({
id: $scope.movieListID.id,
imdb_rating: $scope.movieImdbRating.imdbRating,
title: $scope.movieListID.original_title,
image: $scope.movieListID.poster_path,
movie_id: $scope.movieListID.id,
backdrop: $scope.movieListID.backdrop_path,
overview: $scope.movieCredits.overview
});
})
这有助于保持代码平坦和整洁
this helps keeping your code flatten and clean
这篇关于如何在Angular中链接多个HTTP调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文