Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use Observable vs EventEmitter vs Dot Rule for change detection in angular2

Tags:

angular

There are three methods I have seen to manage change detection in Angular2.

  1. Observables

    @Injectable() export class TodosService {     todos$: Observable<Array<Todo>>;     private _todosObserver: any;     private _dataStore: {         todos: Array<Todo>     };      constructor(private _http: Http) {         // Create Observable Stream to output our data         this.todos$ = new Observable(observer =>              this._todosObserver = observer).share();          this._dataStore = { todos: [] };     } } 
  2. EventEmitter.

    @Injectable() class NameService {   name: any;   nameChange: EventEmitter = new EventEmitter();   constructor() {     this.name = "Jack";   }   change(){     this.name = "Jane";     this.nameChange.emit(this.name);   } } 
  3. Dot Rule

    export interface Info {    name:string; }  @Injectable() class NameService {   info: Info = { name : "Jack" };   change(){     this.info.name = "Jane";   } } 

My question is, all three implementations can work when subscribing to watch changes in data. How do you decide when to use one instead of the other, and what are the drawbacks of each.

like image 946
B Hull Avatar asked Jan 11 '16 08:01

B Hull


People also ask

Is an EventEmitter and 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.

What is the purpose of 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.

What is difference between subject and EventEmitter?

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

What is observable angular12?

Observables provide support for passing messages between parts of your application. They are used frequently in Angular and are a technique for event handling, asynchronous programming, and handling multiple values.


2 Answers

Let's try to give you some hints...

The main problem with the last approach is that it doesn't work with primitive types but only with references. So I wouldn't recommend it...

I think that EventEmitter / Observable is the right approach to implement and handle custom events. It's also linked to components themselves (@Ouput), bidirectional mapping in templates (syntax [(...)]) and the async pipe.

From the documentation, the EventEmitter uses Observable but provides an adapter to make it work as specified here: https://github.com/jhusain/observable-spec. After looking at the EventEmitter class of Angular2, it extends the Subject class. It's a bit more than a simple Observable. See this link for more details: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/subjects.md

Regarding the creation of a custom observable, I would say: create your own observables only when you need something specific. Otherwise leverage the EventEmitter class. But there is a lot of things that you can do with the EventEmitter class and observable operators.

To conclude, on such a "simple" use case, things aren't so obvious but on more complex scenarios, EventEmitter / Observable allow to define an handling chain using operators. The classical sample is to update a list according to a value for an input (here this.term defined in the ngModel of the field):

this.term.valueChanges      .debounceTime(400)      .flatMap(term => this.dataService.getItems(term))      .subscribe(items => this.items = items); 

This great blog post from Christoph Burgdorf could give you some ideas about what observables can handle: http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html.

Hope it helps you, Thierry

like image 75
Thierry Templier Avatar answered Sep 28 '22 17:09

Thierry Templier


Adding to the above, we need to use Event Emitter for event binding between a child and parent component. Its better we avoid subscribing to it, as if and when it is deprecated in future, the code would need to be changed again. So better avoid using Event emitters except for event binding between a child and parent component. In other scenarios it best to use Observable's. Please check this link for details... https://www.bennadel.com/blog/3038-eventemitter-is-an-rxjs-observable-stream-in-angular-2-beta-6.htm#comments_47949

like image 35
Abdur Rahman Avatar answered Sep 28 '22 17:09

Abdur Rahman