多个 httpclient post 调用 foreach 循环 angular 5

multiple httpclient post call into foreach loop angular 5

我需要在 foreach 循环中使用 httpclient。 有可能的?什么是正确的方法? 这是我的代码:

this.attachToDelete.forEach( 
          element => {
            this.documentService.DeleteAttachment(element, this.newDocumentId.toString());
            console.log("upload delete from submit", element);
          }
        );

这是通信服务中的方法:

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

既然开始了,我再细说一下:)

您似乎已成功创建 HTTP 调用,恭喜。

当您创建一个 HTTP 调用时,您就创建了一个 Observable。 Observables 就像 promises,但它们做的更多。

Observable 的问题是,您需要订阅它们才能触发它们。

这可以通过使用 subscribe 链接 HTTP 调用来完成:

this.documentService
  .DeleteAttachment(element, this.newDocumentId.toString())
  .subscribe(response => {...})

response 将包含您的 back-end return。

但我建议您立即进行每个 HTTP 调用。这可以通过在 Observable 的原型上使用一个名为 forkJoin 的方法来完成。

如果您使用 forkJoin,您将需要创建一个调用数组,如下所示:

const calls = [];
this.attachToDelete.forEach(element => {
  calls.push(this.documentService.DeleteAttachment(element, this.newDocumentId.toString()));
});
Observable.forkJoin(calls).subscribe(responses => {...});

这一次,响应将是您的每一个电话的数组,按照您将它们放入数组的方式排序。

希望对您有所帮助,如果没有,欢迎随时提问!

(这意味着您还需要从您的服务中删除整个 subscribe,因为如果不这样做,您将不会 return 一个可观察的而是一个订阅)

具有一些更复杂行为的替代方法:

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