Angular 如何使forEach等待订阅完成?

Angular 如何使forEach等待订阅完成?,angular,asynchronous,promise,async-await,subscribe,Angular,Asynchronous,Promise,Async Await,Subscribe,我用的是Angular 6,我的数据库是Firebase。现在我试着根据建筑来显示每个房间的名字。例如: Building A Room 1 Room 2 Building B Room 1 Room 2 但每次我尝试时,它都会先显示所有建筑的名称,然后才显示房间的名称。这就是我现在得到的: Building A Building B Room 1 Room 2 我发现这是因为forEach一直跳过subscribe函数 我尝试使用promise和wait,但它不起作用。也许是因为我用错了?

我用的是Angular 6,我的数据库是Firebase。现在我试着根据建筑来显示每个房间的名字。例如:

Building A
Room 1
Room 2
Building B
Room 1
Room 2
但每次我尝试时,它都会先显示所有建筑的名称,然后才显示房间的名称。这就是我现在得到的:

Building A
Building B
Room 1
Room 2
我发现这是因为
forEach
一直跳过
subscribe
函数

我尝试使用
promise
wait
,但它不起作用。也许是因为我用错了?我不太清楚如何正确使用
promise

异步加载数据(){
此文件为.navigationService.user
.subscribe(用户=>{
console.log(用户);
this.user=用户;
this.navigationService.getBuildings(this.user.orgId)
.subscribe(building=>{
this.navMasterBuilding=[];
这个。建筑物=建筑物;
this.buildings.forEach(异步构建2=>{
this.completeBuildingId=building2.completeBuildingId;
this.buildingName=building2.buildingName;
console.log(building2.buildingName);
等待新的承诺((决定,拒绝)=>{
this.navigationService.getLocation(this.user.orgId,this.completeBuildingId)
.订阅(位置=>{
控制台日志(房间+位置);
this.navMasterLocation=[];
});
解决();
});   
});
});
});
}

我尝试使用setTimeout来延迟它,但它仍然不起作用。

数组。forEach
仅适用于同步函数。将其更改为使用的for…语法,该语法确实有效。接下来,在调用
getLocation
完成并且
subscribe
中的代码运行之前,您将
解析
承诺。在
getLocation.subscribe
中,将代码更改为调用
resolve

<规范>适用于(建筑施工2){ console.log(building2.buildingName); 等待新的承诺((决定,拒绝)=>{ this.navigationService.getLocation(this.user.orgId,this.completeBuildingId) .订阅(位置=>{ 控制台日志(房间+位置); this.navMasterLocation=[]; 解决(); }); }); }
请注意,它可以简化为:

<规范>适用于(建筑施工2){ console.log(building2.buildingName); const location=等待this.navigationService.getLocation(this.user.orgId,this.completeBuildingId).toPromise(); 控制台日志(房间+位置); this.navMasterLocation=[]; }

还要注意,我不太清楚为什么要使用
this.completeBuildingId
而不是局部变量。考虑到它在每次迭代中都会被覆盖,这对我来说似乎有点无用。

Array.forEach
只适用于同步函数。将其更改为使用的for…语法,该语法确实有效。接下来,在调用
getLocation
完成并且
subscribe
中的代码运行之前,您将
解析
承诺。在
getLocation.subscribe
中,将代码更改为调用
resolve

<规范>适用于(建筑施工2){ console.log(building2.buildingName); 等待新的承诺((决定,拒绝)=>{ this.navigationService.getLocation(this.user.orgId,this.completeBuildingId) .订阅(位置=>{ 控制台日志(房间+位置); this.navMasterLocation=[]; 解决(); }); }); }
请注意,它可以简化为:

<规范>适用于(建筑施工2){ console.log(building2.buildingName); const location=等待this.navigationService.getLocation(this.user.orgId,this.completeBuildingId).toPromise(); 控制台日志(房间+位置); this.navMasterLocation=[]; }

还要注意,我不太清楚为什么要使用
this.completeBuildingId
而不是局部变量。考虑到它在每次迭代中都会被覆盖,这对我来说似乎有点没用。

请将您的代码添加到问题中,而不仅仅是您的代码的照片。可能重复尝试的
resolve()在内部订阅下?我尝试了
resolve()在内部订阅下,但它仍然不起作用。感谢您的建议。请将您的代码添加到问题中,而不仅仅是您的代码的照片。可能重复了Tryed
resolve()在内部订阅下?我尝试了
resolve()在内部订阅下,但它仍然不起作用。谢谢你的建议。这很有效!!!谢谢David Walschots。。你刚刚解决了我的问题。。通过对…使用
。。。的
,并将解析移到内部订阅,它确实有效。。非常感谢你!它工作!!!谢谢David Walschots。。你刚刚解决了我的问题。。通过对…使用
。。。的
,并将解析移到内部订阅,它确实有效。。非常感谢你!