gpt4 book ai didi

javascript - Angular 4 数组值丢失

转载 作者:行者123 更新时间:2023-11-28 17:48:27 25 4
gpt4 key购买 nike

我有一个方法,它将从 http 请求返回的数组分配给另一个数组。问题在于,该方法完成后,包含新值的数组似乎变空。

带有http请求的方法。

loadBookingFullRowDataRequest(rowId: number) {
this.bookingFullRowData[rowId] = [];
this.bookingService.getAllBookingData().subscribe(res => {
this.bookingFullRowData = <Booking[]>res[rowId];
console.log('all booking data: ', this.bookingFullRowData, 'rowId: ', rowId);
for (const item of this.bookingFullRowData) {
const itemId = `${item['title']}-rowid-${item['rowid']}-proj-${item['proj']}`;
this.bookingsForm.addControl(itemId, new FormControl(
`${item['content']}`
));
}
});
}

data logged to the console

尝试使用更新后的数组中的数据的方法。

launchModal(element) {

const elementId = (event.target as Element).id;
const elementIdArray = String(elementId).split('-');
this.currentRow = parseInt(elementIdArray[2], 10);
this.loadBookingFullRowDataRequest(this.currentRow);
console.log('the whole loaded dta:', this.bookingFullRowData, 'row: ', this.currentRow);

this.modalService.createModal('#bookings-form', null, this.dialogOptions);
}

console.log 仅输出一个空数组。

最佳答案

问题在于 getAllBookingData 方法是异步的。这意味着它发出请求但不会立即得到响应。

我们传递给订阅方法的函数基本上是一个回调函数,在返回响应时执行。

这意味着里面的代码

this.bookingService.getAllBookingData().subscribe()//<-- 这里

在稍后的某个时间点执行。

因此此行之后的所有代码:

this.loadBookingFullRowDataRequest(this.currentRow);
// Any code below here!!
console.log('the whole loaded dta:', this.bookingFullRowData, 'row: ', this.currentRow);

this.modalService.createModal('#bookings-form', null, this.dialogOptions);

在传递到订阅方法的函数之前执行。

因此,要解决您的问题,您需要移动回调函数中检索数据后需要执行的所有代码:

loadBookingFullRowDataRequest(rowId: number) {
this.bookingFullRowData[rowId] = [];
this.bookingService.getAllBookingData().subscribe(res => {
this.bookingFullRowData = <Booking[]>res[rowId];
console.log('all booking data: ', this.bookingFullRowData, 'rowId: ', rowId);
for (const item of this.bookingFullRowData) {
const itemId = `${item['title']}-rowid-${item['rowid']}-proj-${item['proj']}`;
this.bookingsForm.addControl(itemId, new FormControl(
`${item['content']}`
));
}
console.log('the whole loaded dta:', this.bookingFullRowData, 'row: ', this.currentRow);

this.modalService.createModal('#bookings-form', null, this.dialogOptions);

});
}

顺便说一句,不要使用 .toPromise 坚持使用 Observables。

关于javascript - Angular 4 数组值丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46169048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com