我正在尝试从我拥有的数组中对 api 发出放置请求。帖子想要一个对象,而我有一个对象数组。我所做的是一个循环,迭代调用该方法的对象数组的长度到我的服务中。问题是第一个只工作,其余的都不起作用。我是否应该像返回承诺这样的东西,然后递归地调用它?
在这里,我让我的方法调用 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));
}
正如我所说,它只是返回我我们所做的第一篇文章,其余的都没有被创建。
多谢!
您可以使用
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));
}