import {Injectable} from '@angular/core'; import {FirebaseAuth, AngularFire} from "angularfire2"; import {Subject, Observable, BehaviorSubject} from "rxjs"; import {AuthInfo} from "./auth-info"; @Injectable() export class AuthService { static UNKNOWN_USER = new AuthInfo(null); authInfo$: BehaviorSubject = new BehaviorSubject(AuthService.UNKNOWN_USER); constructor(public auth: FirebaseAuth, public af: AngularFire) { this.af.auth.subscribe(auth => { if (auth) { const authInfo = new AuthInfo(auth.uid); this.authInfo$.next(authInfo); } else { this.authInfo$.next(AuthService.UNKNOWN_USER); } }); } login(email: string, password: string) { return this.fromFirebaseAuthPromise(this.auth.login({email, password})); } fromFirebaseAuthPromise(promise): Observable { const subject = new Subject(); promise .then(res => { subject.next(res); subject.complete(); }, err => { subject.error(err); subject.complete(); }); return subject.asObservable(); } logout() { this.af.auth.logout(); } }