为什么事件发射器不返回第一个值?



我在eventemitter方面遇到了一个问题,即当我在子类中添加数据并通过eventemitter将数据传递给父级时,我面临的问题是,当子级添加时,父级无法获得第一个数据,第一个数据是子级添加的,当第二个数据添加到子级时,才到达父级

子组件

saveData()
{
this.dialog.closeAll();
this.getData();
const body={
name:this.model.name,
age:this.model.age
}
// this.arrayCalendar.push(body);
this.calendarService.previewdata.emit(body)
}

父组件

handleDateClick(arg) {
const data={};
this.dialog.open(AddPatientComponent,{
data:{data},
width:"200px",
height:"300px"
})
this.calendarService.previewdata.subscribe(message => this.result = message);
console.log("DATA FROM PARENT"+JSON.stringify(this.result))
if(this.result)
{
this.calendarEvents = this.calendarEvents.concat({ 
title: this.result.name,
start: arg.date,
allDay: arg.allDay
})
}

}

服务

constructor() { }
public previewdata = new EventEmitter();

有人知道这背后的原因吗?

您应该将依赖于EventEmitter值的代码移动到订阅块中。

this.calendarService.previewdata.subscribe(message => this.result = message);
console.log("DATA FROM PARENT"+JSON.stringify(this.result))
if(this.result)
{
this.calendarEvents = this.calendarEvents.concat({ 
title: this.result.name,
start: arg.date,
allDay: arg.allDay
})
}

应该是

this.calendarService.previewdata.subscribe(message => {
this.result = message;
console.log("DATA FROM PARENT"+JSON.stringify(this.result))
if(this.result)
{
this.calendarEvents = this.calendarEvents.concat({ 
title: this.result.name,
start: arg.date,
allDay: arg.allDay
})
}
});

老实说,我建议进行一些认真的重构。如果你想使用emitter,那么在没有服务的情况下使用它,这是一种奇怪的设计。

其次,不要订阅处理单击的函数。如果你不正确取消订阅,这可能会导致奇怪的行为,就像你现在所经历的那样。

如果您想使用服务,请删除emitter,并将其替换为一些主题和可观察的内容。

服务:

private _previewData: Subject<any> = new Subject<any>(); //use proper type instead of any
previewData$: Observable<any> = this._previewData.asObservable(); //same here
constructor() {}
// and correct type here instead of any
pushUpdate(dialogData: any): void {
this._previewData.next(dialogData);
}

子级:

saveData(): void {
// I'm not sure what dialog you use but I have a feeling that the code below
// should be moved to subscribe or then
this.dialog.closeAll();
this.getData();
const body = {
name:this.model.name,
age:this.model.age
}
this.calendarService.pushUpdate(body);
}

父级:

ngOnInit() {
this.calendarService.previewData$
.pipe(
// Add console log to see what data are pushed
tap(data => console.log('previewData:', data)),
// Remove if it fails for no obvious reason and do the check in subscribe
filter(data => !!data)
)
.subscribe(message => {
// Do whatever you want to do with your data here
this.result = message
if (this.result) {
this.calendarEvents = this.calendarEvents.concat({ 
title: this.result.name,
start: arg.date,
allDay: arg.allDay
});
});
}
handleDateClick(arg) {
const data={};
this.dialog.open(AddPatientComponent, {
data:{data},
width:"200px",
height:"300px"
});
// It looks like you are using Angular Material, have you tried 
// handling data returned from dialog in aferClosed() observable?
// dialog.afterClosed().subscribe(result => {...});
}

最新更新