Unable to figure out correct EventEmitter or Observable Syntax in Angular2 Services
Actually it's almost the same thing, there a few changes
createUser(user: any): any { return new Observable.create(observer => { this.ref.createUser(user, function(error, userData) { if (error) { observer.error(error); console.log("Error creating user:", error); } else { observer.next('success'); observer.complete(); console.log('Successfully created user account with uid:', userData.uid); } }); }) }
And then you can suscribe
to it (subscribe
is the equivalent of then
).
Here's a plnkr with an example using Observables
constructor() { this.createUser({}).subscribe( (data) => console.log(data), // Handle if success (error) => console.log(error)); // Handle if error}
EventEmitter
on the other hand is a Subject
(documentation differs a little bit since angular2 moved to the last version, but it's still understandable).
_emitter = new EventEmitter();constructor() { // Subscribe right away so we don't miss the data! this._emitter.toRx().subscribe((data) => console.log(data), (err) => console.log(err));}createUser(user: any) { this.ref.createUser(user, function(error, userData) { if (error) { this._emitter.throw(error); console.log('Error creating user:", error'); } else { this._emitter.next(userData); this._emitter.return(); This will dispose the subscription console.log('Successfully created user account with uid:', userData.uid); } }) }
Here's a plnkr with an example using EventEmitter.
The difference in super short : Observable starts emitting the data when it finds subscribers; Subject emits info whether there are subscribers or not.
Note
In the EventEmitter example I used toRx()
. This exposes the Subject
but it's being refactored and we won't need toRx()
anymore.
Useful resources Updated
RxJS In-Depth by Ben Lesh in AngularConnect's 2015 conference.
Thanks to Rob Wormald for pointing out this
You can see Sara Robinson's talk and her demo app and see it running here