如何在处理到下一步之前等待 HTTP 请求在循环中获得响应 [英] how to wait for HTTP requests to get response in a loop before its processes to next step

查看:42
本文介绍了如何在处理到下一步之前等待 HTTP 请求在循环中获得响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何等待 HTTP 请求获得响应.我正在尝试使用循环多次进行 API 调用,但我没有获得准确的数据.没有按照request.required值(如o,1,2,3,4(索引)及其返回值如2,1,3,4)排列.

how to wait for HTTP requests to get response.I'm trying to make API calls several time using loop but I did not get exact data the values ill-received based on the execution time of the API call means the values, not arranged according to request.required value like o,1,2,3,4 (index) and its return values like 2,1,3,4.

    var l=0 ; 
  for (var k=0;k<this.imagesdataarray.length;k++ ){

   this.http.post('http://api.interiordesigns2020.com/api/services/app/DesignerProject/Create',{
      name: this.imagesdataarray[k].projecttitle,
      designerCategoryID: this.imagesdataarray[k].categoryid,
      userID: this.userid
      
    })
    .subscribe(res => { 
   
        this.data1=res;
        this.imagesdataarray[l].projectid=this.data1.result.id;
        l++;
    }
    );
   
    } 

推荐答案

你应该使用 forkJoin() 来运行一个 observable 数组.

You should use forkJoin() for something like this to run an array of observables.

这里有一个关于 StackBlitz 的例子:https://stackblitz.com/edit/angular-ivy-t7phj1?file=src/app/app.component.ts

Here's an example on StackBlitz: https://stackblitz.com/edit/angular-ivy-t7phj1?file=src/app/app.component.ts

 array = [1, 2, 3, 4, 5];

  ngOnInit() {
    forkJoin(
      this.array.map(i =>
        this.http.get<any[]>(`https://jsonplaceholder.typicode.com/todos/${i}`)
      )
    ).subscribe(response => console.log(response));
  }

这篇关于如何在处理到下一步之前等待 HTTP 请求在循环中获得响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆