[英]Sending multiple GET requests with changing parameter in AngularJS
編輯 :對回答者表示歉意,事實證明這實際上是有效的代碼,但是請求被攔截並剝奪了所有參數。
我正在嘗試對REST API進行重復的HTTP GET請求,具體取決於輸出,並已使用此問題的解決方案。
但是,我希望增加我在請求中傳遞的參數之一。 本質上,API分頁輸出,我需要相應地增加startAt
的值。
手動請求可以正常使用:
<URL>/board?startAt=50
並退還:
{"maxResults":50,"startAt":50,"isLast":true,"values":[list_of_values]}
到目前為止,這是我的代碼:
function getHttpPromise(start_at) {
// This function recurses until the server returns isLast = true.
//
// Each iteration appends the values in response.values to
// $scope.boards.
test = $http({
url: 'boards',
method: 'GET',
params: {'startAt': start_at.toString()}
}).
success(function (response) {
console.log(response); // the response contains startAt, which always has
// the initial value (0), rather than start_at's value
var values = response.values;
for (var i in values) {
var board = values[i];
$scope.boards[board.id] = board;
}
if (response.isLast) {
// We have received all the boards.
return true;
} else {
// Increment start_at and return another http request promise.
start_at += response.maxResults;
return getHttpPromise(start_at);
}
}
);
console.log(test); // params is correct here
return test;
}
該函數的調用者:
jiraWorkLog.controller('SprintSelectCtlr',
function($scope, $http, $routeParams) {
$scope.init = function() {
$scope.boards = new Object();
getHttpPromise(0).then(
function (dummy_var) {
for (var board in $scope.boards) {
...
}
}
);
}
...
);
$http().success()
已棄用。 您應該使用$http().then()
。
then
該函數將接收一個函數,該函數將被傳遞一個具有名為data
的屬性的response
對象。 在這里您將找到自己的values
。
您可以在這里進一步閱讀
徹底閱讀代碼后,我必須建議您不要遞歸解決此問題。 如果您不希望分頁數據,請提前發送所有記錄的請求。
現在回答為什么只得到第一個結果:這是因為這是唯一返回的結果,並且是調用控制器的結果。 您返回的承諾是控制器正在等待解決。 所有其他遞歸調用僅在您的控制器已經完成之后才發生。
響應包含所有http內容,您想從中獲取數據...
我認為以下鏈接可能對您有所幫助Angular Http
遞歸的另一個問題是您正在更新局部變量並錯誤地使用了它。
function getHttpPromise(start_at) {
// This function recurses until the server returns isLast = true.
//
// Each iteration appends the values in response.values to
// $scope.boards.
test = $http({
url: 'boards',
method: 'GET',
params: {'startAt': start_at.toString()}
}).
success(function (response) {
console.log(response.data); // the response contains startAt, which always has
// the initial value (0), rather than start_at's value
var values = response.data;
for (var i in values) {
var board = values[i];
$scope.boards[board.id] = board;
}
if (response.data.isLast) {
// We have received all the boards.
return true;
} else {
// Increment start_at and return another http request promise.
return getHttpPromise(response.data.maxResults+1);
}
}
);
console.log(test); // params is correct here
return test;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.