Eventemitter angular 4 does not work

0

I have a Profile.service that issues an event to two components that do not communicate. By clicking on the ProfileComponent link, it triggers the "ProfileService.emitBeneficies.emit ('profile.benefits')" and redirects to theComponentOptionalProfile. However, the content in the console.log does not appear. However, if I come back and do it again, it will issue.

// ProfileService

constructor(private authService: AuthService, private config: AppConfig,  private http: HttpClient, private router: Router ){ }

static emitirBeneficios = new EventEmitter();

// ProfileComponent    

redirect(perfil: Perfil) {
    PerfilService.emitirBeneficios.emit(perfil.beneficiosOpcionais)
    this.router.navigate(['/perfil/opcionais']);

// ProfileOptionalComponent

ngOnInit() {
    PerfilService.emitirBeneficios.subscribe(beneficiosOpcionais => 
    console.log(beneficiosOpcionais));
  }
    
asked by anonymous 29.03.2018 / 18:13

2 answers

0

Using EventEmitter in a service is considered an bad practice . Basically, EventEmitter is an Angular framework abstraction and its sole purpose is to output events to components.

Angular will never guarantee that EventEmitter will remain a Observable . This means that it is necessary to refactor the code if it changes. The only API that should be accessed is the emit() method, and you should never perform subscribe manually. In addition, the correct thing is to use EventEmitter only for event binding between a parent component and a child component.

In this case, I recommend using BehaviorSubject or ReplaySubject .

    
29.03.2018 / 18:34
0

Good morning

@Output() emitter: EventEmitter<any> = new EventEmitter<any>();

The eventEmitter must be an Output since it will send a response and needs to be imported as

import { EventEmitter } from '@angular/core';

But the practice of EventEmitter is for the communication between components by HTML, where you need to generate a selector with @Input () to execute a procedure where it will return with an @Output () through the EventEmitter for the element Father ( emitter)="namename (value)".

    
06.09.2018 / 15:45