2017-04-10 62 views
0

我需要一個情況來處理,我需要一個循環執行多次http獲取調用。這裏是我的代碼同步http獲取調用與循環在Angular js離子

for(i = 1; i <= 5; i++){ 
    console.log(i); 
    var req = { 
     method: 'GET', 
     timeout: 30000, 
     url: url 
     params: {page_id: i} 
     }; 
     $http(req).success(function(data, status, headers, config) { 
      console.log(data); 
     }).error(function(data, status, headers, config) { 
      console.log('error'); 
     });  
    } 

我需要這個來處理,但沒有得到值的順序。

回答

1

在循環使用的函數調用,示例如下:

function httpRequestFn(req) { 
    $http(req).success(function(data, status, headers, config) { 
     console.log(data); 
    }).error(function(data, status, headers, config) { 
     console.log('error'); 
    }); 
} 

for(i = 1; i <= 5; i++){ 
    console.log(i); 
    var req = { 
     method: 'GET', 
     timeout: 30000, 
     url: url 
     params: {page_id: i} 
    }; 
    httpRequestFn(req); 
} 
0
,如果你想發送多個請求的一個鏡頭,然後我會建議使用 $q.all

var httpArr = []; 
for (i = 1; i <= 5; i++) { 
    console.log(i); 
    var req = { 
     method: 'GET', 
     timeout: 30000, 
     url: url 
     params: { 
      page_id: i 
     } 
    }; 
    httpArr.push($http(req)) 
} 
$q.all(httpArr).then(function(response) { 
    console.log(response[0].data) // 1st request response 
    console.log(response[1].data) // 2nd request response 
    console.log(response[2].data) // 3rd request response 
}).catch(function(response) { 
    //error resonse 
}) 

確保注入

$q至控制器