![](/img/trans.png)
[英]Angular 2 http Observable request not returning response header
[英]how to wait for http request for returning response with in subscribe method in angular 8?
在我的情況下,我會獲取數據,但是當我調用第一個 HTTP 請求時,數據沒有按照我想要的請求排序沒有為我的數組分配正確的 ID。
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關鍵字一起使用。 在移動到下一個循環並發送新請求之前,它將等待請求完成。
var res= await this.http
.post('http://api.interiordesigns2020.com/api/services/app/ImageProject/CreateProjectImages', fd).toPromise();
imagename.imageid = res.result;
請記住相應地使用async關鍵字。
這是我的方式:
this.imagename.imageid = await new Promise<any>(resolve => this.http.post('http://api.interiordesigns2020.com/api/services/app/ImageProject/CreateProjectImages', fd)
.subscribe( res => { resolve(res.result);
//imagename.imageid = res.result;}
));
// Remaining code or function call
請將 Observable 轉換為 Promise 不是一個好的解決方案。 observables 的偉大之處在於您可以加入、合並、forkjoin、swhitchMap..
在這種情況下,您應該使用 map 創建一個可觀察數組並使用forkJoin進行唯一訂閱
//create an array of observables
const obs$=this.imagesdataarray.map(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);
return this.http.post('http://.....', fd)
})
//subscribe to a forkJoin of the array of observables
//"res" is an array with the response to the first call, the second call..
//so you can in subscribe use some like:
forkJoin($obs).subscribe((res:any[],index)=>{
this.imagesdataarray[index].response=res[index];
})
順便說一句,您可以直接使用 - 這不是必需的 formData-
const obs$=this.imagesdataarray.map(imagename =>{
const fd = {'userID':this.userid,
'projectID':imagedata.projectid,
'id':imagename.imageid,
'formFiles':imagename.image
}
return this.http.post('http:...', fd)
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.