我的代码有问题。它说我的数组是未定义的,但是稍后有一个方法可以正常工作。这是代码:
books: IBook[] = [];
[...]
ngOnInit() {
this.service.getEmployees().subscribe(
(listBooks) => this.books = listBooks,
(err) => console.log(err)
);
}
[...]
events: CalendarEvent[] = [
{
start: new Date(),
end: new Date(),
title: ""+this.books[0].device, //this.books[0] is undefined
color: colors.yellow,
actions: this.actions,
resizable: {
beforeStart: true,
afterEnd: true
},
draggable: true
},
[...]
test(){ //this method is linked to a button
console.log(this.books[0]) //after clicking it works fine
}
[...]
Test方法位于数组之后,它说它是“未定义的”,所以它不能被不确定吗?
答案 0 :(得分:2)
您在代码中的哪个位置执行此操作? :
events: CalendarEvent[] = [
{
start: new Date(),
end: new Date(),
title: ""+this.books[0].device, //this.books[0] is undefined
color: colors.yellow,
actions: this.actions,
resizable: {
beforeStart: true,
afterEnd: true
},
draggable: true
},
[...]
如果此代码位于ngOnInit方法中,则应将其放入订阅回调中,如下所示:
ngOnInit() {
this.service.getEmployees().subscribe(
(listBooks) => {
this.books = listBooks
[...]
events: CalendarEvent[] = [
{
start: new Date(),
end: new Date(),
title: ""+this.books[0].device, //this.books[0] is undefined
color: colors.yellow,
actions: this.actions,
resizable: {
beforeStart: true,
afterEnd: true
},
draggable: true
},
[...]
},
(err) => console.log(err)
);
}
getEmployees的调用是异步的,这意味着可以在初始化books对象的回调函数之前初始化event对象。 希望清楚
答案 1 :(得分:0)
首先,在getEmployees()
中运行的ngOnInit
是异步的。浏览器将继续同步执行events
分配,但是稍后将在调用中解决listBooks
。
因此,在解决数据之后,您应该修正逻辑并初始化events
,并可能在未定义的情况下处理所需的信息:
title: this.books[0] ? ""+this.books[0].device : ""
最后,当您要分配新数据时,需要对books
进行不可变的操作:
this.books = [...listBooks]