gpt4 book ai didi

angular - 数组长度显示为零,即使数组不为空

转载 作者:行者123 更新时间:2023-12-02 16:59:37 25 4
gpt4 key购买 nike

我可以在控制台中打印数组,但无法获取长度,也无法访问第一个元素

我正在做一个项目,我遇到了这个问题,我可以在控制台中打印数组,但我无法获取长度,也无法访问第一个元素。

代码:

checkout.component.ts:

ngOnInit() {
this.booksInCheckout = this.checkoutService.getCheckoutBooks();
console.log(this.booksInCheckout); // for array
console.log(this.booksInCheckout.length); // for length of array
console.log(this.booksInCheckout[0]); // for first element
}

checkout.service.ts:

getCheckoutBooks(): Checkout2[] {
console.log('hey hello');
this.booksInCheckout1 = [];
this.booksInCheckout2 = [];
this.userID = +localStorage.getItem('id');
this.userService.getUserById(this.userID).subscribe(user => {
this.booksInCheckout1 = user.checkout;
for (let i = 0; i < this.booksInCheckout1.length; i++) {
this.bookService
.getBook(this.booksInCheckout1[i].bookId)
.subscribe(book => {
this.daysRemaining = Math.ceil(
Math.abs(
new Date(
this.booksInCheckout1[i].endDate
).getTime() - this.today.getTime()
) / this.ONEDAY
);
this.booksInCheckout2.push(
new Checkout2(
book,
new Date(
this.booksInCheckout1[i].startDate
).getMonth() +
1 +
'/' +
new Date(
this.booksInCheckout1[i].startDate
).getDate() +
'/' +
new Date(
this.booksInCheckout1[i].startDate
).getFullYear(),
new Date(
this.booksInCheckout1[i].endDate
).getMonth() +
1 +
'/' +
new Date(
this.booksInCheckout1[i].endDate
).getDate() +
'/' +
new Date(
this.booksInCheckout1[i].endDate
).getFullYear(),
this.booksInCheckout1[i].status,
this.daysRemaining
)
);
});
}
console.log(this.booksInCheckout2.length);
});

return this.booksInCheckout2;
}

enter image description here

最佳答案

发生这种情况是因为您没有在等待服务。发生的情况是数据并非来自服务器,您正在控制台记录其值。

let fetchData=async (params:any)=>{
this.booksInCheckout = await this.checkoutService.getCheckoutBooks();// getting array value service
//other code here
}

async function fetchData( params:any)=>{
this.booksInCheckout = await this.checkoutService.getCheckoutBooks();// getting array value service
//other code here
}

为您的服务使用下面提到的函数实现之一。

//code for service 
function getCheckoutBooks(){
return http.get();
}



async function getCheckoutBooks(){
const booksData : any = await http.get();

return booksData;
}

下面的代码应该可以工作。

ngOnInit() {
this.checkoutService.getCheckoutBooks().subscribe((booksInCheckout)=>{
console.log(booksInCheckout); // for array
console.log(booksInCheckout.length); // for length of array
console.log(booksInCheckout[0]); // for first element

});

}

您遇到这个问题是因为您正在调用一个异步函数,但由于 javascript 的异步特性,函数下面的代码会在异步任务完成之前执行。

所以我在这里为异步任务添加了一个回调。希望对您有所帮助:)

关于angular - 数组长度显示为零,即使数组不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54741882/

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