首页 > 解决方案 > 即使数组不为空,数组长度也显示为零

问题描述

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

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

代码:

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
}

结帐.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;
}

在此处输入图像描述

标签: angulartypescript

解决方案


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

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 的异步特性,函数下面的代码在异步任务完成之前被执行。

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


推荐阅读