如何在循环Angular

时间:2017-05-23 07:58:28

标签: api angular post promise

我正在尝试从我拥有的数组向api执行put请求。帖子想要一个对象,我有一个对象数组。我所做的是循环迭代我的对象数组的长度,将方法调用到我的服务中。问题是,第一个工作正常,其余工作不正常。我是否应该返回承诺,然后递归调用它?

这里我让我的方法调用api:

onUpdate() {
for (var i = 0; i < this.conditionsToUpdate.length; i++) {
      this.ruleService.updateConditionsFromRule(this.rule.id, this.conditionsToUpdate[i])
    .then(_ => {
      this.notificationService.addToast('Condition Updated!', '', 2)
    })
    .catch(err => this.notificationService.handleError("Could not update the 
      condition!"))
 }
}

最后,在我的服务上,我有我的要求:

updateConditionsFromRule(idRule: number, condition: ConditionUpdate):Promise<any> {
 return this.http.post(`${this.organizationId}/rules/${idRule}/conditions`, condition)
  .toPromise()
  .then(res => {
    const response = <{ id: String, error: IError[] }>res.json();
    if (!!response && !!response.error) {
      return Promise.reject(response.error)
    } else {
      return Promise.resolve(response)
    }
  }).catch(err => Promise.reject(err));
 }

就像我说的那样,它只是让我回复了我们做的第一篇文章,其余的都没有创建。

非常感谢你!

1 个答案:

答案 0 :(得分:0)

你可以使用Observable,承诺太有限了。

给定数组updateConditionsFromRule,这就是如何实现这样的事情:

let requests:Observable<Response>[] = [];
updateConditionsFromRule.forEach( updateCondition => {
  requests.push(this.http.post(`${this.organizationId}/rules/${idRule}/conditions`, condition));
});

// After our loop, requests is an array of Observables, not triggered at the moment.

//Now we use combineLatest to convert our Observable<Response>[] to a Observable<Response[]>.
//This means that the promise will resolve once the last request of the array has finished.

Observable.combineLatest(requests).toPromise()
  .then(res => {
    const response = <{ id: String, error: IError[] }>res.json();
    if (!!response && !!response.error) {
      return Promise.reject(response.error)
    } else {
      return Promise.resolve(response)
    }
  }).catch(err => Promise.reject(err));
 }