Angular Eventemitter 4 does not work

Asked

Viewed 745 times

0

I have a.service Profile that broadcasts an event for two components that don’t communicate. By clicking on the Profile Component link, it triggers the "Perfilservice.emitirBeneficios.Emit('profile.benefitsOpcionais')" and redirects to Perfilopcionaiscomponent. However, the content does not appear on the console.log. However, if I go back and do it again, it emits.

//Profiling

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

static emitirBeneficios = new EventEmitter();

//Profile

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

//Perfilopcionaiscomponent

ngOnInit() {
    PerfilService.emitirBeneficios.subscribe(beneficiosOpcionais => 
    console.log(beneficiosOpcionais));
  }

2 answers

0

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

Angular will never assure us that EventEmitter will continue to be a Observable. This means that it is necessary to refactor the code if it changes. The only API that should be accessed is the method emit(), being that you should never perform the subscribe manually. Additionally, it is correct to use EventEmitter only for Event Binding between a parent component and a child component.

In this case, I recommend using the BehaviorSubject or of ReplaySubject.

0

Good morning

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

eventEmitter needs to be an Output since it will send a reply and needs to be imported as

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

However, the practice of Eventemitter is for communication between HTML Components, where you need to generate a selector with @Input() to execute a procedure where it will return with a @Output() through the Eventemitter to the Parent (emitter) element= "dometode(value)".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.