angularangular5angular-event-emitter

Angular 5 event emitter triggered twice


I am using angular 5. In which I am passing data from one component to another component using eventemitter.

At first click event emitter is not subscribe the value in child component. On second click event emitter triggered twice.

Header component.ts

 this.testservice.sendsearchdata.next( this.searchdataform.value)

Search component.ts

this.testservice.sendsearchdata.subscribe(value=>{ 
    console.log( value)
})

testservice.ts

  public testservice: EventEmitter<any> = new EventEmitter ():

While passing reactive form data from header component to search component it's not triggered at first click. On next click it has triggered twice.


Solution

  • I think you are incorrectly using EventEmitter. It's used when child component emitting events to parent component via @Output() property. In your case, component communication realized by using service. Try this way:

    @Injectable()
    export class MissionService {
    
      // Observable string sources
      private missionAnnouncedSource = new Subject<string>();
      private missionConfirmedSource = new Subject<string>();
    
      // Observable string streams
      missionAnnounced$ = this.missionAnnouncedSource.asObservable();
      missionConfirmed$ = this.missionConfirmedSource.asObservable();
    
      // Service message commands
      announceMission(mission: string) {
        this.missionAnnouncedSource.next(mission);
      }
    
      confirmMission(astronaut: string) {
        this.missionConfirmedSource.next(astronaut);
      }
    }
    

    Parent and children communicate via a service