I need to use httpclient into foreach loop. It is possible? What is the right way? Here is my code:
this.attachToDelete.forEach(
element => {
this.documentService.DeleteAttachment(element, this.newDocumentId.toString());
console.log("upload delete from submit", element);
}
);
and this is the method in correspondig service:
public DeleteAttachment(attachmentId: number, documentId: string) {
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
return this.http.post('http://localhost:8080/DocumentAPI/api/document/RemoveAttachment?docId=' + documentId + '&attachmentId='+attachmentId, attachmentId, { headers: headers }).subscribe(
data => {
if(data)
console.log("delete attach????", data);
else{
console.log('Error occured');
}
}
);
}
Since you start, I will elaborate a little :)
You seem to have succeed creating an HTTP call, congratulations on that.
When you create an HTTP call, you create an Observable
. Observables are like promises, but they do more.
The thing with observables is, that you need to subscribe to them to trigger them.
This can be done by chaining the HTTP call with subscribe
:
this.documentService
.DeleteAttachment(element, this.newDocumentId.toString())
.subscribe(response => {...})
response
will contain your back-end return.
But what I would advise you, is to makre every HTTP call at once. This can be done by using a method on the prototype of Observable, called forkJoin
.
If you use forkJoin, you will need to create an array of calls, like so :
const calls = [];
this.attachToDelete.forEach(element => {
calls.push(this.documentService.DeleteAttachment(element, this.newDocumentId.toString()));
});
Observable.forkJoin(calls).subscribe(responses => {...});
This time, responses will be an array of each and everyone of your calls, ordered by how you put them into the array.
I hope this helps, if not, feel free to ask anything !
(This means you also need to remove the whole subscribe
from your service, because if you don't, you will not return an observable but a subscription)