Search code examples
javascriptangulartypescriptobservableangular-event-emitter

Emit method of EventEmitter not emitting values to subscribers


So I am trying to connect two components through a service, LoaderComponent and AppComponent with LoaderService, so that when app fetches data a loader shows up. But when I try to use an EventEmitter to emit changes to the components they don't get the changes but when the service subscribes to itself, it can get the changes

LoaderService.ts

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

@Injectable()

class LoaderService {
  @Output change: EventEmitter<number> = new EventEmitter<number>();
  private state: number = 0;

  constructor() { 
     this.change.subscribe(state => console.log(state)); 
     this.setState(1) 
  }

  setState(state: number) {
     this.state = state;
     this.change.emit(this.state);
  }
}
// Shows state when  but outside of the service event is not detected, also tried EventEmitter from from events

I expect to get events from the LoaderService to subscribers


Solution

  • You need to use LoaderService in some component for angular to create it, if we do not use the service any where angular will automatically discard it. Inject LoaderService in app component like below:

    constructor(private _loadService: LoaderService) {} and then you will see the console.log().

    Also, it is recommended to use either Subject or Behavior Subject from Rxjs instead of Output in a service.