Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular component: Can I use an Observable instead EventEmitter as @Output() property?

[angular 2.4.5]

I tried and it seems to work like an EventEmitter:

  • My component from outside:

    <split (visibleTransitionEnd)="log($event)"></split> 
  • Inside the component:

    @Output() visibleTransitionEnd: Observable<string> observer: Observer;  constructor() {   const myObs = new Observable(observer => this.observer = observer);    this.visibleTransitionEnd = myObs     .map(x => '> ' + x + ' <')     .debounceTime(20)     .do(() => console.log('here we are!')); } 
  • Then I can call inside component:

    // needed condition because if nobody subscribe 'visibleTransitionEnd' > no observer! if(this.observer) this.observer.next('test'); 

View this plunker

I like this because there's no subscription inside my component.

But is it a bad way to achieve this? What's the risk/wrong?

Is it better to use a Subject?

like image 351
bertrandg Avatar asked Feb 08 '17 16:02

bertrandg


People also ask

Is an EventEmitter an observable?

EventEmitter is used in the directives and components to emit custom events either synchronously or asynchronously. Since EventEmitter class extends RxJS subject class, this means it is observable and can be multicasted to many observers.

Should I use EventEmitter or subject?

Conclusion. Use Eventemitter when transferring data from child component to parent component. Use Subject to transfer data from one component to another component.

What is the use of observable in Angular?

Angular makes use of observables as an interface to handle a variety of common asynchronous operations. For example: The HTTP module uses observables to handle AJAX requests and responses. The Router and Forms modules use observables to listen for and respond to user-input events.

Why do we use EventEmitter in Angular?

EventEmitterlink. 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.


1 Answers

EventEmitter just extends Subject, so this is no surprise (and I also saw this already in Dart).

They use their own class to be able to alter the implementation later without breaking existing code.

So it might not be the best idea to circumvent this abstraction. If you are aware of the disadvantage and willing to accept it, you can of course do it.

like image 53
Günter Zöchbauer Avatar answered Sep 21 '22 13:09

Günter Zöchbauer