我订阅了observable,然后将数据放入一个数组(array_item)。在第二个foreach()中,我遍历数组以获取我的数据,但它从未执行过,因为数组仍然是空的。我的意思是执行转移到这个foreach(),而我还没有收到我的所有数据。在继续第二个foreach()和操作数组(array_item)项之前,我怎样才能让它等到收到所有数据并在数组中。
names: any[] = [];
array_item: any[] = [];
drawtimeline(nom_cal, _hitoService, idcalbuscador) {
this.names.forEach((ev) => {
groups.add([{id: ev._id, content: ev.nom_calendario, cal_id: ev._id}]);
var g = ev._id;
for (var i = 0; i < this.names.length; i++) {
this._hitoService.getHitos(this.names[i]._id)
.subscribe(hito1 => {
this.hito1 = hito1
this.array_item.push(hito1);
});
}
console.log("before 2nd foreac()");
for (var j = 1; j < this.array_item.length; j++) {
console.log("inside 2nd foreac()");
this.array_item[j].forEach((item) => {
console.log("i = " + i + " id_item: " + this.calendarObject._id + " j =" + j);
items.add([{
id: i,
group: g,
start: item.start_datetime,
end: item.end_datetime,
style: itemStyle(item.design),
className: "pepe"
}]);
console.log("i = " + i + "id_item: " + this.calendarObject._id);
});
}
});
}
答案 0 :(得分:1)
任何依赖于异步进程的代码都必须在异步进程完成后才能调用。要等待所有响应,您可以使用forkJoin:RxJS Observable.forkJoin
import {Observable} from 'rxjs';
const requests = Observable.forkJoin(this.names.map(name => this._hitoService.getHitos(name._id)));
requests.subscribe(responses => { <do stuff with responses here> });
响应将是每次调用_hitoService.getHitos
的响应数组答案 1 :(得分:1)
import {Observable} from 'rxjs/Observable';
names: any[] = [];
array_item: any[] = [];
drawtimeline(nom_cal, _hitoService, idcalbuscador) {
this.names.forEach((ev) => {
groups.add([{
id: ev._id,
content: ev.nom_calendario,
cal_id: ev._id
}]);
var g = ev._id;
Observable.forkJoin(this.names.map(v => {
return this._hitoService.getHitos(v._id)
.map(hito1 => {
this.hito1 = hito1;
this.array_item.push(hito1);
})
})).subscribe(res => {
console.log("before 2nd foreac()");
for (var j = 1; j < this.array_item.length; j++) {
console.log("inside 2nd foreac()");
this.array_item[j].forEach((item) => {
console.log("i = " + i + " id_item: " + this.calendarObject._id + " j =" + j);
items.add([{
id: i,
group: g,
start: item.start_datetime,
end: item.end_datetime,
style: itemStyle(item.design),
className: "pepe"
}]);
console.log("i = " + i + "id_item: " + this.calendarObject._id);
});
}
});
})
}