如何在Angular 8中使用subscribe方法等待http请求返回响应? [英] how to wait for http request for returning response with in subscribe method in angular 8?

查看:81
本文介绍了如何在Angular 8中使用subscribe方法等待http请求返回响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的情况下无法获取数据,但是当我调用第一个HTTP请求时,数据没有按照我想要的请求进行排序,它首先将值分配回我的数组,然后移至下一个API调用,但是在这种情况下,不能排序或没有为我的数组分配正确的ID.

In my case ill get data but the data did not sort according to the request I want when I call the first HTTP request it first assigns value back to my array then moves to the next API call but in this case, the data comes unsorted or did not assign the right id to my array.

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( async (res) => {
imagename.imageid = await res.result;
});

})
});

推荐答案

在这种情况下,您需要使用 toPromise() await 关键字.在进入下一个循环并发送新请求之前,它将等待请求完成.

You need to use toPromise() in this case with await keyword. It will wait for request to complete before moving to next loop and sending new request.

var res= await this.http
.post('http://api.interiordesigns2020.com/api/services/app/ImageProject/CreateProjectImages', fd).toPromise();

imagename.imageid = res.result;

请记住相应地使用 async 关键字.

Remember to use async keyword accordingly.

这篇关于如何在Angular 8中使用subscribe方法等待http请求返回响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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