Observable.forkJoin(this.cdsDataService.getServersForComponent().map(one => this.Servers = one),
this.cdsDataService.getComponentForServer().map(two => this.Components = two))
.subscribe(res => {
//for these ids more http calls are made
for (let comp of this.Components) {
this.compIds.push(comp.ID);
//does not wait for this http call to complete
this.getObjectsById();
SomeMethod();
}}
);
getObjectsById()
{
let observableBatch = [];
this.compIds.forEach((key) => {
observableBatch.push(this.cdsDataService.getComponentLinks(key).subscribe(p => {
//console.log(key);
for (let it of p) {
let nodelink = {from: key, to: it.ID, color: "blue"};
this.componentLinkData.push(nodelink);
}
// console.log(p);
}));
});
return Observable.forkJoin(observableBatch);
}
getComponentForServer()
返回getObjectsById()
中使用的ID
getObjectsById()
遍历id,并为每个id进行http调用。
我无法让程序等待来自getObjectsById()
的所有调用结束。
它只是跳到SomeMethod()
;
我们将不胜感激。
答案 0 :(得分:2)
您要订阅的是每个请求,而不是forkjoin
。
this.compIds.forEach((key) => {
observableBatch.push(this.cdsDataService.getComponentLinks(key));
});
return Observable.forkJoin(observableBatch).subscribe((p: any[]) => {
//console.log(key);
for (let it of p) {
let nodelink = { from: key, to: it.ID, color: "blue" };
this.componentLinkData.push(nodelink);
}
// console.log(p);
});
答案 1 :(得分:1)
您实际上是在mimetypes
内进行subscribe()
。由于subscribe()
调用是异步的,因此无需等待结果即可执行代码。
改为使用http
或switchMap
:
concatMap
答案 2 :(得分:0)
尝试一下:
Observable.forkJoin(
this.cdsDataService.getServersForComponent().map(one => this.Servers = one),
this.cdsDataService.getComponentForServer().map(two => this.Components = two))
).switchMap(() => {
return Observable.forkJoin(this.Components.map(c => {
return this.cdsDataService.getComponentLinks(c.ID).tap(links => {
links.forEach(link => {
let nodelink = {from: c.ID, to: link.ID, color: "blue"};
this.componentLinkData.push(nodelink);
});
});
}));
}).subscribe(() => {
console.log('I am done!');
SomeMethod();
});
不使用可插值语法,因为您的原始代码不是。