【问题标题】:How to call a post method from api in a loop Angular如何在循环Angular中从api调用post方法
【发布时间】:2017-10-23 01:34:06
【问题描述】:

我正在尝试从我拥有的数组中向 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));
 }

正如我所说,它只是将我们发布的第一个帖子返回给我,其余的都没有创建。

非常感谢!

【问题讨论】:

    标签: api angular post promise


    【解决方案1】:

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

    给定你的数组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));
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      • 2016-11-17
      • 2018-12-07
      相关资源
      最近更新 更多