2

I just updated my application to Angular 16, which uses a lot of EventEmitter in a service to show where the user is in the app (setting Boolean values). signals were added in this release and I am trying to understand the benefits of switching. The code appears to be simpler.

Their guide for "Sharing data between child and parent directives and components" still uses EventEmitter.

xinthose
  • 3,213
  • 3
  • 40
  • 59
  • 1
    As I understand it, signals is in "developer preview" in v16 ... so isn't fully documented yet. But if you find a specific place that should be documented, it may be helpful to open an issue on GitHub. – DeborahK Jun 08 '23 at 05:15

2 Answers2

0

I just updated my application to Angular 16, which uses a lot of EventEmitter in a service

EventEmitter isn't to be used in services, it's to be used with components so you can add event listeners from HTML:

Use in components with the @Output directive to emit custom events synchronously or asynchronously, and register handlers for those events by subscribing to an instance.

Source: docs

Use a signal or a(n) Observable/Subject. Choosing between these two is a longer debate. Signals are still in preview, though they're making quite an impression on the Angular ecosystem, it's a safe bet they're here to stay. An Observable carries the power of RxJS to process streams of data. So, whatever suits your need best, really.

J.P.
  • 5,567
  • 3
  • 25
  • 39
0

There are differences between observables and signals:

  • Signals always have value;
  • Signals don't push the new value - they notify their consumers, but the consumer should pull the value. Because of this, the consumer can only read the latest value, not every update that happened before the value was pulled;
  • Signals don't have the "complete" state.

For example, if you would track keydown events using signals, you would not be able to collect information on what keys were pressed between the moments when you read the signal.

If you would try to use a signal for a network request, you would quickly find out that your signal should have the value before you get the response, and that you can not detect if the request is completed. You could use undefined as an initial value, but that would be a one-time signal usage - that's not what they are designed for, and it wouldn't resolve the "completeness" issue for the requests that can return more than one response.

As far as I understand, you use EventEmitter to represent the application state ("where the user is located in any moment of time"), so signals should be a good fit here - there will be always an initial value, there is no "complete" stage for this information. The only thing you need to change if you don't need to know about every change of this information and react to every change (as we often do in the case of router events).

OZ_
  • 12,492
  • 7
  • 50
  • 68