I'm having a hard time finding much in the way of examples/guides for using observables in an Angular2 service. There is stuff for html templates binding with EventEmitter but that doesn't seem right for a service.
One of the big driving themes is getting away from Promises in Angular2 but I can't seem to get the new syntax correct.
What I'm Doing
- I have a FirebaseAuth Service that can be injected into other services or components.
- I have a function that does an async call to firebase, in my example to create a user
- I want to return a Observable(to replace the promise) that other services can use to do other things like create a profile when this is resolved
I'm fine if promises are the best solution for this example but I'd like to figure out what the Observable Way is.
My Service:
/*DS Work on firebase Auth */
import {Injectable} from 'angular2/angular2';
@Injectable()
export class FirebaseAuth {
ref = new Firebase('https://myfirebase.firebaseio.com');
//check if user is logged in
getAuth(): any {
return this.ref.getAuth();
}
//register a new user
createUser(user: any): Promise<any> {
return new Promise((resolve, reject) => {
this.ref.createUser(user, function(error, userData) {
if (error) {
reject(error);
console.log('Error creating user:", error');
} else {
resolve(userData);
console.log('Successfully created user account with uid:', userData.uid);
}
})
})
}
};
How would I rewrite this to use Observable and/or EventEmitter?
Actually it's almost the same thing, there a few changes
And then you can
suscribe
to it (subscribe
is the equivalent ofthen
).Here's a plnkr with an example using Observables
EventEmitter
on the other hand is aSubject
(documentation differs a little bit since angular2 moved to the last version, but it's still understandable).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 theSubject
but it's being refactored and we won't needtoRx()
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