import { Injectable } from '@angular/core' ; import { Http } from '@angular/http' ; import { Observable } from 'rxjs' ; import { map } from 'rxjs/operators/map' ; import { FirebaseApp } from "angularfire2" ; import { AngularFireAuth } from "angularfire2/auth" ; import { AngularFireDatabase , AngularFireObject , AngularFireList } from "angularfire2/database" ; import { BaseService } from "./base.service" ; import { User } from './../models/user.model' ; import * as firebase from 'firebase/app' ; import 'firebase/storage' ; @ Injectable ( ) export class UserService extends BaseService { users : Observable < User [ ] > ; currentUser : AngularFireObject < User > ; constructor ( public afAuth , public db , public firebaseApp , public http ) { super ( ) ; this . listenAuthState ( ) ; } private setUsers ( uidToExclude ) { this . users = this . mapListKeys < User > ( this . db . list < User > ( `/users` , ( ref ) => ref . orderByChild ( 'name' ) ) ) . map ( ( users ) => { return users . filter ( ( user ) => user . $key !== uidToExclude ) ; } ) ; } private listenAuthState ( ) { this . afAuth . authState . subscribe ( ( authUser ) => { if ( authUser ) { console . log ( 'Auth state alterado!' , authUser . uid ) ; this . currentUser = this . db . object ( `/users/${ authUser . uid }` ) ; this . setUsers ( authUser . uid ) ; } } ) ; } create ( user , uuid ) { return this . db . object ( `/users/${ uuid }` ) . set ( user ) . catch ( this . handlePromiseError ) ; } edit ( user ) { return this . currentUser . update ( user ) . catch ( this . handlePromiseError ) ; } userExists ( username ) { return this . db . list ( `/users` , ( ref ) => ref . orderByChild ( 'name' ) . equalTo ( username ) ) . valueChanges ( ) . map ( ( users ) => { return users . length > 0 ; } ) . catch ( this . handleObservableError ) ; } get ( userId ) { return this . db . object < User > ( `/users/${ userId }` ) ; } uploadPhoto ( file , userId ) { return this . firebaseApp . storage ( ) . ref ( ) . child ( `/users/${ userId }` ) . put ( file ) ; } }