Last active
May 12, 2017 22:22
-
-
Save codediodeio/0921b135c13fa8711e990c23aa22f144 to your computer and use it in GitHub Desktop.
AngularFire2 Auth service that merges custom data from the database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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