angularrxjsevent-handlingrxjs-observablesangular-event-emitter

Which would be better to use : EventEmitter or service?


I'm learning angular framework and I was wondering in this scenario which would be better to use. Child component gets 3 inputs ( name, date, age) but has no click event ( From what I gather you can still emit without such a event in said component) and needs to pass data to a parent component which will generate some sort of profile. The parent component does have a submit button which I assume I could use with the child component but unsure if that's a code smell. Would a shared service be more suitable?

I've had a look at some examples of child to parent data transmission using event emitters but most seem to have a button in the child component.


Solution

  • So it depends on your code, project, and what you like :-). A Subject/Observable in a service is a better EventEmitter so to say. And I say it in short, so don't think a EventEmitter is bad or wrong, it isnt't.

    So if your component communicate directly with his parent, a EventEmitter can be enough and do its job. It's very reusable and a good practice. If you component is used in many parent components and all need to react to any event, of the event goes up over more components (child -> parent -> parent2) then you can use a service instead a EventEmitter.

    In most cases a EventEmitter is used by a very reusable component that not know about its parent as example. A service is used by centralized things, or our component know that it must to communicate with other reusable components eventually. So a service is the better approach.