我想检查一个数组,直到填充并显示一个加载对话框,但它总是告诉我
this.events [0]是未定义的
ngOnInit() {
this.initMethod();
if(this.events[0].start == this.books[0].date_from_og) {
this.dialog.closeAll();
}
}
,但事件不能被不确定,因为它包含显示的日历的事件。
initMethod() {
this.service
.getEmployees()
.subscribe(
(listBooks) => {
this.books = listBooks;
this.events = this.books.map((book) => {
return {
start: new Date(book.date_from_og),
end: new Date(book.date_to_og),
type: ""+book.type,
title: "" + book.device + "",
color: colors.blue,
actions: this.actions,
resizable: {
beforeStart: false,
afterEnd: false
},
draggable: false
}
});
},
(err) => console.log(err)
);
}
}
和构造函数:
constructor(private modal: NgbModal, private service: BookingService, private dialog: MatDialog) {
this.initMethod();
this.dialog.open(DialogLaedt, {
width: '650px'
});
您的问题是您 initMethod()
异步检索结果。
因此,当您使用if(this.events[0].start == ...
到达线时,无法保证已从服务中检索事件数据。
修复程序是将您的支票移入init方法的订阅一部分(在可观察到其值的值后立即执行(,或让Init方法返回可以订阅的可观察到的可观察到的,并在内部执行检查该订阅。
解决方案1-将检查入住订阅
ngOnInit() {
this.initMethod();
}
initMethod() {
this.service
.getEmployees()
.subscribe(
(listBooks) => {
this.books = listBooks;
this.events = this.books.map((book) => {
return {
start: new Date(book.date_from_og),
end: new Date(book.date_to_og),
type: ""+book.type,
title: "" + book.device + "",
color: colors.blue,
actions: this.actions,
resizable: {
beforeStart: false,
afterEnd: false
},
draggable: false
}
if(this.events[0].start == this.books[0].date_from_og) {
this.dialog.closeAll();
}
});
},
(err) => console.log(err)
);
}
解决方案2-让您的inithod返回可观察的
ngOnInit() {
this.initMethod().subscribe(() => {
if(this.events[0].start == this.books[0].date_from_og) {
this.dialog.closeAll();
}
});
}
initMethod() {
return this.service
.getEmployees()
.pipe(tap(
(listBooks) => {
this.books = listBooks;
this.events = this.books.map((book) => {
return {
start: new Date(book.date_from_og),
end: new Date(book.date_to_og),
type: ""+book.type,
title: "" + book.device + "",
color: colors.blue,
actions: this.actions,
resizable: {
beforeStart: false,
afterEnd: false
},
draggable: false
}
});
}))
}
我已经注意到您两次调用 initmethod(( inithod((。一次进入构造函数,一次在 ngoninit 方法中。