如何遍历API响应并将响应值分配给angular 8中的嵌套数组 [英] How to iterate through an API response and assign response value to nested array in angular 8

查看:50
本文介绍了如何遍历API响应并将响应值分配给angular 8中的嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在循环中多次调用API,并且在响应时,我将项目ID分配回数组,但是m的值在运行第二个循环之前已经增加,并且引发错误TypeError:无法读取未定义的属性"imagesnamearray".

I'm trying to make API call several time in a loop and at the response, I assign the project id back to the array but the value of m incremented already before running the second loop and that throws an error TypeError: Cannot read property 'imagesnamearray' of undefined.

var  m = 0;
for (var j=0 ; j<this.imagesdataarray.length;j++){
  var n=0;
  for (var i=0;i<this.imagesdataarray[j].imagesnamearray.length;i++){
    const fd = new FormData();
    fd.append('userID',this.userid );
    fd.append('projectID', this.imagesdataarray[j].projectid);
    fd.append('id',this.imagesdataarray[j].imagesnamearray[i].imageid);
    fd.append('formFiles', this.imagesdataarray[j].imagesnamearray[i].image );

    this.http.post('http://api.interiordesigns2020.com/api/services/app/ImageProject/CreateProjectImages',fd)
    .subscribe(async (res) => {
      this.data=res;
      this.imagesdataarray[m].imagesnamearray[n].imageid=this.data.result; 
      n++;
    });
    
  }
  m++;

}

推荐答案

问题是 m 是全局变量,而您的回调( subscribe 的参数)是异步执行.

The problem is that m is a global variable and your callback (the argument to subscribe) is executed asynchronously.

您的代码首先会创建大量HTTP请求,从而在此过程中增加 m n .有时稍后,HTTP请求完成,并调用您的回调.到那时, m 不再具有启动请求时的值.

Your code first creates a lot of HTTP requests, increasing m and n in the process. Sometimes later, the HTTP requests complete and your callback is called. By that time, m no longer has the value it had when you started the request.

我将按照以下方式重写您的代码.我还用 Array.forEach 替换了 for 循环.

I would rewrite your code as follows. I have also replaced your for loop with Array.forEach.

this.imagesdataarray.forEach(imagedata => {
  imagedata.imagesnamearray.forEach(imagename => {
    const fd = new FormData();
    fd.append('userID', this.userid );
    fd.append('projectID', imagedata.projectid);
    fd.append('id', imagename.imageid);
    fd.append('formFiles', imagename.image);

    this.http
      .post('http://api.interiordesigns2020.com/api/services/app/ImageProject/CreateProjectImages', fd)
      .subscribe(data => {
        imagename.imageid = data.result; 
      });
  })
});

这篇关于如何遍历API响应并将响应值分配给angular 8中的嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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