2017-05-23 8 views
0

나는 배열에있는 API에 대한 put 요청을 수행하려고합니다. 게시물은 객체를 원하며 객체 배열을 가지고 있습니다. 내가하는 일은 메서드를 내 서비스로 호출하는 객체 배열의 길이를 반복하는 루프입니다. 문제는 단지 첫 번째로 작동하고 나머지는 작동하지 않는다는 것입니다. 반환 약속 같은 것을해야하고 재귀 적으로 호출 할 수 있습니까?루프에서 api에서 post 메서드를 호출하는 방법 각도

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를 호출하자 나머지는 생성되지 않습니다.

정말 고마워요!

답변

0

Observable을 사용하면 약속이 너무 제한 될 수 있습니다.

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)); 
} 
:

이 배열 updateConditionsFromRule 주어진이 그런 일을 구현하는 방법입니다

관련 문제