简体   繁体   中英

why EventEmitter doesn't return first value?

I have a problem with eventemitter , that is when i add data in child class and passes the data into parent by EventEmitter , i am facing a problem that parent is not able to get first data when child add, the first data was child added only getting to parent when second data added in child

Child Components

    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)
               }

parent component

      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
  })
}

}

service

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

Anyone Know the reason behind that?

You should move the code that depends on the EventEmitter's value inside the subscribe block.

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
  })
}

should be

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
      })
    }
});

Honestly I would suggest some serious refactoring. If you want to use emitter use it without the service, that's some weird design.

Second, don't subscribe in the function which handles click. This might lead to weird behavior, like what you experiencing now, if you don't unsubscribe properly.

If you want to use service, remove the emitter and replace it with some subject and observable.

Service:

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);
}

Child:

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);
}

Parent:

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 => {...});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM