简体   繁体   English

对每个数组项进行api调用

[英]make api call for each item of array

I have an array of object of days, I want to make separate HTTP call for each array item. 我有一个天对象数组,我想为每个数组项单独调用HTTP。 but the condition is when I get the previous items success response then only I want to make next items API request till I want to wait. 但条件是当我得到之前的项目成功响应然后我只想做下一个项目API请求,直到我想等待。 suppose I have 5 items in my array so it will make API call immediately. 假设我的数组中有5个项目,因此它会立即进行API调用。 I want that each items API request sequentially. 我希望每个项目API请求顺序。 means when my first items API requests response is true then second items API should call. 表示当我的第一个项目API请求响应为真时,则第二个项目API应该调用。

I have used a for & for each loop and traverse each array item & make HTTP post call but it don't wait for previous requests success response. 我已经使用for和for each循环并遍历每个数组项并进行HTTP post调用,但它不等待先前的请求成功响应。

 // component call daysArr = [ { day: 'Monday', date: '20-10-2018' }, { day: 'Tuesday', date: '21-10-2018' }, { day: 'Wednesday', date: '22-10-2018' }, { day: 'Thursday', date: '23-10-2018' }, { day: 'Friday', date: '24-10-2018' }, { day: 'Saturday', date: '25-10-2018' }, { day: 'Sunday', date: '26-10-2018' } ] postCall() { let apiUrl = 'https:someurl.com/api/dayspost'; for (let i = 0; i < this.daysArr.length; i++) { // how to check previous request response & make request for next array element this.service.createPost(apiUrl,this.daysArr[i]) .subscribe(response => { console.log('response',response) }) } } //service post call createPost(url, post) { return this.http.post(url,post) .pipe( map(data => { return data; }) ) } 

above is the snippet which displays the API request. 上面是显示API请求的代码段。 but I don't understand how can I check my previous response & then only make new API/post call for new array element. 但我不明白如何检查我之前的响应,然后只为新的数组元素进行新的API / post调用。

Thank you. 谢谢。

You can do something like this: 你可以这样做:

let i = 0;
makeRequest(apiUrl, this.daysArr[i]){
  this.service.createPost(apiUrl,post)
    .subscribe(response => {
       console.log('response',response)
       i++;
       if(i < this.days.length){
          makeRequest(apiUrl, this.daysArr[i])
       }
  })
}

I have no IDE right now to try this, but it should work fine 我现在没有IDE尝试这个,但它应该工作正常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM