0

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

2 Answers 2

12

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)

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks @trichetriche! I try now!
@user3669577 don't edit my post, edit yours or leave me a comment ! And I don't have access to images, so post your stack trace in text so that I can read it !
@user3669577 I try your code, but I get this error: Observable.forkJoin is not a function you need to import the forkjoin with this : import 'rxjs/add/observable/forkJoin';
Forgive me, @trichetriche!! I'm still very cumbersome! Symply I add import 'rxjs/add/observable/forkJoin'; and slightly modified your code. Now all is fine. Many thanks! You're great!
No problem, glad I could help !
|
0

An alternate with some more complex behaviors:

  async onDeletePress() {
    let deletedList : Observable<MyObject>[] = [];

    this.selectedArray?.forEach(i_obj => {deletedList.push(this._service.deleteObj(<string>i_obj.Id));});

    forkJoin(deletedList).subscribe(async () => {      
      this.gridObjects = await this.fetchRecentList();
      this._snackBar.open('Objects Deleted', '', { duration: 2000 });
    });
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.