Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

232
Vistas
How to subscribe to event emitter once?
// Part of service
public someEvent: EventEmitter<number> = new EventEmitter();

....

// Component
@Component({
  selector: 'some-component',
  template: `...`
})
export class SomeComponent {
  constructor(public service: Service) {
    this.service.someEvent.subscribe((x) => {
      // Do something
    });
  }
}

SomeComponent is displayed in / route. When I navigate to different route in my application, and come back again, SomeComponent will subscribe to the event again, causing callback to fire twice. How to subscribe to the event once or unsubscribe on destroy of the component and subscribe again?

// Can't subscribe after.
ngOnDestroy() {
  this.service.someEvent.unsubscribe();
}
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

A call to subscribe returns an instance of Disposable, which has a method dispose.

Or if you are using RxJS 5, dispose has been renamed to unsubscribe (thanks @EricMartinez).

And from the RxJS docs:

...when we're no longer interested in receiving the data as it comes streaming in, we call dispose on our subscription.


Store the result of your call to subscribe and later dispose of the subscription within ngOnDestroy.

RxJS 5:

export class SomeComponent implements OnDestroy {
  constructor(public service: Service) {
    this.subscription = this.service.someEvent.subscribe((x) => {...});
  }
  ngOnDestroy() {
      this.subscription.unsubscribe();
  }
}

RxJS <5:

export class SomeComponent implements OnDestroy {
  constructor(public service: Service) {
    this.subscription = this.service.someEvent.subscribe((x) => {...});
  }
  ngOnDestroy() {
      this.subscription.dispose();
  }
}
over 4 years ago · Santiago Trujillo Denunciar

0

You can do something like this:

import { OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Rx';

export class SomeComponent implements OnDestroy {
  private _subscription: Subscription;
  constructor(public service: Service) {
    this._subscription = this.service.someEvent.subscribe((x) => {
      // Do something
    });
  }
}

ngOnDestroy(){
  this._subscription.unsubscribe();
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda