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