angular - 即使数组不为空,数组长度也显示为零
问题描述
我可以在控制台中打印数组,但无法获取长度,也无法访问第一个元素
我正在做一个项目,我遇到了这个问题,我可以在控制台中打印数组,但我无法获得长度,我也无法访问第一个元素。
代码:
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;
}
解决方案
发生这种情况是因为您没有等待服务。发生的情况是数据不是来自服务器,而您正在控制台记录其值。
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 的异步特性,函数下面的代码在异步任务完成之前被执行。
所以在这里我为异步任务添加了一个回调。希望能帮助到你 :)
推荐阅读
- algebra - 为什么 Y(O_Y) 的层,作为 X 的一个封闭子方案,不一定是仿射的,是准相干的?
- java - 从命令行调用jar的lib文件夹中的jar类?
- php - 尝试使用 Codeigniter 从 JSON 保存数据时找不到对象
- shell - 使用 Unix shell 脚本的 FTP,然后触发任务
- python - 我想用 start 命令运行我的 python 程序(不是脚本),这是要执行的 python 程序文件中的一种方法
- php - ManyToMany关系连接三个表,结果限制了mysql中第三个表的第三个表限制
- java - com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 键 'PRIMARY' 的重复条目 '0'] 有根本原因
- c# - 单击 VR 中的游戏对象并做某事
- powershell - 有什么方法可以更改 Powershell ISE 的突出显示颜色?
- r - 将 df$var 传递给函数时,是否可以获得“var”的名称?