Skip to content

Instantly share code, notes, and snippets.

@codediodeio
Last active May 12, 2017 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codediodeio/0921b135c13fa8711e990c23aa22f144 to your computer and use it in GitHub Desktop.
Save codediodeio/0921b135c13fa8711e990c23aa22f144 to your computer and use it in GitHub Desktop.
AngularFire2 Auth service that merges custom data from the database
import { Injectable } from '@angular/core';
import { AngularFireAuth } from "angularfire2/auth";
import { AngularFireDatabase } from "angularfire2/database";
import * as firebase from 'firebase';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
export class User {
uid: string;
username:string;
email:string;
constructor(uid, username, email) {
this.uid = uid
this.username = username || ""
this.email = email || ""
}
}
@Injectable()
export class AuthService {
_userSource = new BehaviorSubject(null);
currentUser = this._userSource.asObservable();
constructor(public afAuth: AngularFire,
private db: AngularFireDatabase,
private router:Router) {
afAuth.authState.subscribe( (auth) => {
this.buildUser(auth)
});
}
private buildUser(auth) {
// retrieves custom user data from the realtime database
if (auth) {
this.db.object(`users/${auth.uid}`).subscribe((data) => {
let user = new User(data.$key, data.username, data.email)
this._userSource.next(user)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment