I was using EventEmitter
and @Output
in Angular services, today one of the coleagues mentioned it's not a good practice.
I found this post mentioning it's a bad practice and it seems mostly is personal opinion, and this answer is mentioning it's OK to use it.
I couldn't find any official document about it, so if somebody knows an official answer for it please post.
Official doc about EventEmittter
I was using EventEmitter and @Output in Angular services, today one of the coleagues mentioned it's not a good practice.
The annotation @Output()
has no effect in a service. It is used to tell the Angular template compiler to bind an Observable
to a template expression.
If I saw @Output()
in a service, then I'd tell the developer to remove it.
EventEmitter
is an Observable
and there are no side effects in using it in a service, but there are also no benefits.
You can use any Observable
type of emitter in either a component or service. There are two reasons why we have EventEmitter
. 1) it pre-dates the Angular teams decision to commit to using observables and they thought they might need their own implementation, 2) it can emit values in the next JavaScript cycle (optional setting).
There were edge cases were people needed to emit changes in the next cycle to avoid problems with change detection.
Secure Your Observables
@Injectable()
export class MyService {
public events: Subject<any> = new Subject();
}
The problem with the above service is that anyone can emit values from the public events
. You want your service to be the only code that handles emitting values.
@Injectable()
export class MyService {
private _events: Subject<any> = new Subject();
public get events(): Observable<any> {
return this._event;
}
}
The above is better because access to the Subject.next(..)
is private. Consumers can only subscribe to the observable.
If you followed the components approach. It forces you to expose your emitter which isn't a good idea.
@Injectable()
export class MyService {
@Output() // <<< has no effect
public events: EventEmitter<any> = new EventEmitter();
// ^^ makes the emitter public
}
Components need to have their properties as public if they are to be used in templates, but this isn't the case for services.