[Fixed] How to subscribe to a private Event Emitter in Angular

Issue

I have a service which has an Event Emitter say "E". Right now E is a public variable. I am on Angular 11.

  • Is there a way I can use public functions to allow other components to subscribe to E and keep E as private?
  • Is it good practice to keep Event Emitters as private, or do we usually have them as public?

P.S. If there are better ways to do this (Observables etc.), go easy on me, I’m taking an Angular course and haven’t reached there yet.

For example, this is my service where I have the Event Emitter

export class ShoppingListService {
    public ingredientsChanged = new EventEmitter<Ingredient[]>();
}

And this is my component where I subscribe to it:

export class ShoppingListComponent implements OnInit {
  ingredients: Ingredient[];

  constructor(private shoppingListService: ShoppingListService) {}

  ngOnInit(): void {
    this.ingredients = this.shoppingListService.getIngredients();

    this.shoppingListService.ingredientsChanged.subscribe(
      (ingredients: Ingredient[]) => {
        this.ingredients = ingredients;
      }
    );
  }
}

Solution

Is there a way I can use public functions to allow other components to
subscribe to E and keep E as private?

Yes, expose it via a function:

getMyPrivateImgredientsChangedEventEmitter(): EventEmitter {
   return this.ingredientsChanged;
}

Then your calling code can do this:

componentInstance.getMyPrivateImgredientsChangedEventEmitter().subscribe((result) => {
  // process result
});

Is it good practice to keep Event Emitters as private, or do we usually have them as public

There are a lot of variables to the decision to keep things private, public, or protected there is no single answer here beyond "it depends"

Generally, if it doesn’t have to be exposed I try not to. But, I also place more restrictions on components optimized for re-use than I do for app specific components.

Event Emitters usually exist so that other, external, components can subscribe to changes inside your component so as a general rule they’ll be public. But, I can also make an argument that it shouldn’t be write-able so a read-only property or one exposed via a method.

Leave a Reply

(*) Required, Your email will not be published