如何在AngularJS中更新单个API请求来传递不同的Query参数?
How can I update a single API request in AngularJS to pass different Query parameters?
我正在使用AngularJS从WordPress.com的REST API中提取帖子。
我想按类别将帖子数据解析为三个部分。
我能够创建一个正确显示帖子的应用程序,但它使用多个$http.get
命令来获取每个部分中的帖子。这将导致一个非常慢的应用程序和大量的冗余。
我如何消除冗余并加快我的应用程序?是否有办法编写几个不同的控制器来更新单个API请求?
下面是我的AngularJS代码:
//Initialize My Angular App
var app = angular.module('myApp', []);
//Create Controllers
app.controller('seeDoInNewOrleansCtrl', function ($scope, $http) {
$http.get('https://public-api.wordpress.com/rest/v1.1/sites/www.gonola.com/posts?category=see-do-in-new-orleans&number=1')
.success(function (response) {
$scope.postData = response;
});
});
app.controller('eatDrinkInNewOrleansCtrl', function ($scope, $http) {
$http.get('https://public-api.wordpress.com/rest/v1.1/sites/www.gonola.com/posts?category=eat-drink-in-new-orleans&number=1')
.success(function (response) {
$scope.postData = response;
});
});
app.controller('musicCtrl', function ($scope, $http) {
$http.get('https://public-api.wordpress.com/rest/v1.1/sites/www.gonola.com/posts?category=music&number=1')
.success(function (response) {
$scope.postData = response;
});
});
这里是myApp的一个小示例:https://jsfiddle.net/tr0sdky1/
简单的答案是将这3个组合到一个控制器中,而不是使用$scope。它们的postData第一个使用$scope.postDataSee
,第二个使用$scope.postDataEat
,第三个使用$scope.postDataMusic
,各自的ng-repeat使用不同的作用域变量。
不那么简单的答案是使用promises和$q all来组合3个请求,然后使用一个中继器来遍历它们。
/
/Initialize My Angular App
var app = angular.module('myApp', []);
//Create Controller
app.controller('postsCtrl', function ($scope, $http, $q) {
var categories = ['See & Do', 'Eat & Drink', 'Music'];
var seePromise = $http.get('https://public-api.wordpress.com/rest/v1.1/sites/www.gonola.com/posts?category=see-do-in-new-orleans&number=1');
var eatPromise = $http.get('https://public-api.wordpress.com/rest/v1.1/sites/www.gonola.com/posts?category=eat-drink-in-new-orleans&number=1');
var musicPromise = $http.get('https://public-api.wordpress.com/rest/v1.1/sites/www.gonola.com/posts?category=music&number=1');
$q.all([seePromise, eatPromise, musicPromise).then(function(results) {
$scope.posts = results;
});
});
和伪html:
<div ng-repeat="category in categories">
<span>{{category}}</span> <!-- Category name and whatever... -->
<div ng-repeat="post in posts[$index]">
<!-- post data -->
</div>
</div>
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- 使用Express捕获参数
- 参数变量出现ngTable指令问题
- AngularJS:我可以跳过函数参数回调吗
- 如何使用skip参数使用angular ui引导进行服务器端分页
- 要求未定义JS回调参数
- 我的jQuery插件参数没有正确启动,遇到了问题
- 获取@ResponseBody的一部分作为主干和Spring MVC控制器之间的参数
- jquery设置为使用参数运行
- Javascript”;类“;带有参数的扩展
- 为什么grunt contrib connect的中间件选项的第三个参数是未定义的
- 函数未将值作为参数传递
- 如何将参数传递到angularJs中的工厂
- 修改req.url;t更新url参数(req.query)
- Firebase 承诺 - Query.once 失败:使用 1 个参数调用.预计至少 2
- 如何使用AngularJS$resource.query传递参数
- 修改req.query.page查询参数,并组成新的URL字符串
- 如何在AngularJS中更新单个API请求来传递不同的Query参数?
- 请求.身体vs请求.参数与request.query
- node.js和PostgreSQL query - throw new TypeError('第一个参数必须是