我有一个在我的ngOnInit
方法中调用的服务。它返回并填充我的数组。然后我使用第一个数组的结果完全调用另一个服务方法,该数组又填充第二个数组。
我的问题是,在渲染我的第二个数组时,我认为它仍然是空的,所以它永远不会渲染到屏幕上。
这是一个简化的示例:
changedBookings: Booking[] = [];
currentBookings: Booking[] = [];
constructor(private bookingService: BookingService) { }
ngOnInit() {
//Get all changes then filter
this.bookingService.getAllHistory()
.subscribe(
data => {
this.changedBookings = (data as any).results
},
err => {
console.log(err);
},
() => {
this.getCurrentBookings();
})
}
getCurrentBookings() {
for(let i of this.changedBookings) {
this.bookingService.getRoomBooking(i.date,i.level,i.room)
.subscribe(
data => this.currentBookings.push((data as any).results),
err => console.log(err),
() => {
//shows this array being filled
console.log(this.currentBookings);
}
)
}
}
<div class="row">
<div *ngFor="let booking of changedBookings">
{{booking.date}}
</div>
<!--This one never shows-->
<div *ngFor="let booking of currentBookings">
{{booking.date}}
</div>
</div>
我该如何编写此代码,以便可以在我的 html 代码中使用这两个数组。
最后轻松修复。但其他人可能会被追上。
getCurrentBookings() {
for(let i of this.changedBookings) {
this.bookingService.getRoomBooking(i.date,i.level,i.room)
.subscribe(
data => this.currentBookings.push((data as any).results),
err => console.log(err),
() => {
//shows this array being filled
console.log(this.currentBookings);
}
)
}
}
由于这是循环,它实际上是在每个循环中推送一个对象数组,因此您最终会得到如下结果:
[ [{}],[{}] ]
那么明显
<div *ngFor="let booking of currentBookings">
{{booking.date}}
</div>
将是未定义的。无需更改任何其他代码即可轻松修复,如下所示:
<div *ngFor="let booking of currentBookings">
{{booking[0].date}}
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句