【问题标题】:multiple httpclient post call into foreach loop angular 5多个httpclient post调用到foreach循环角度5
【发布时间】:2018-03-12 15:03:03
【问题描述】:

我需要在 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');
        } 
      }     
    );
  }

【问题讨论】:

    标签: angular post rxjs httpclient call


    【解决方案1】:

    既然你开始了,我会详细说明:)

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

    当您创建 HTTP 调用时,您会创建一个 Observable。 Observables 类似于 Promise,但它们的作用更多。

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

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

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

    response 将包含您的后端返回。

    但我会建议您一次完成每个 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,因为如果您不这样做,您将不会返回一个可观察的,而是一个订阅)

    【讨论】:

    • 谢谢@trichetriche!我现在试试!
    • @user3669577 不要编辑我的帖子,不要编辑你的帖子或给我留言!而且我无权访问图像,因此请以文本形式发布您的堆栈跟踪,以便我可以阅读!
    • @user3669577 I try your code, but I get this error: Observable.forkJoin is not a function 你需要用这个导入forkjoin:import 'rxjs/add/observable/forkJoin';
    • 原谅我,@trichetriche!我还是很麻烦! Symply 我添加了 import 'rxjs/add/observable/forkJoin';并稍微修改了您的代码。现在一切都很好。非常感谢!你太棒了!
    • 没问题,很高兴能帮上忙!
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-11-13
      • 1970-01-01
      • 2017-01-05
      • 1970-01-01
      • 2014-10-12
      • 2020-05-01
      • 2021-11-18
      • 2018-03-24
      • 1970-01-01
      相关资源
      最近更新 更多