I can print the array in console but I can't get the length and I can't access first element
I am working on a project, I come across with this issue, where I can print the array in console but I can't get the length and I can't access first element also.
code:
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;
}