Global service que teria que carregar tudo antes de inciar
import { Injectable } from "@angular/core";
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/firestore';
import { takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class GlobalService {
docUsuarioLogado;
uidUsuarioLogado;
emailUsuarioLogado;
contaRef: string;
contaId: string;
contaPath: string;
unsubscribeAll: Subject<any> = new Subject();
constructor(private afAuth: AngularFireAuth, private afs: AngularFirestore) {}
/* Set accont data */
/* Set account data */
async setAccountData(): Promise<void> {
this.afAuth.auth.onAuthStateChanged(async user => {
if (user) {
console.log(user);
this.uidUsuarioLogado = user.uid;
this.docUsuarioLogado = this.afs.doc(`usuarios/${user.uid}`).valueChanges();
this.emailUsuarioLogado = user.email;
this.afs
.doc(`usuarios/${user.uid}`)
.snapshotChanges()
.pipe(takeUntil( this.unsubscribeAll))
.subscribe(
(doc: any) => {
this.contaId = doc.payload.data().conta_ref.id;
this.contaRef = doc.payload.data().conta_ref;
this.contaPath = doc.payload.data().conta_ref;
},
error => {
console.log(error.message);
}
);
}
});
}
ngOnDestroy(): void {
this.unsubscribeAll.next();
this.unsubscribeAll.complete();
}
}
Eu preciso usar nesse serviço as variáveis do global service.
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, DocumentData, AngularFirestoreDocument, DocumentReference } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { Ponto } from '../models/ponto.model';
import * as moment from 'moment';
import { GlobalService } from '../core/services/global.service';
import { FirestoreService } from '../core/services/firestore.service';
@Injectable()
export class MainService {
dateTime = new Date();
momentDate = moment(this.dateTime).format('YYYY-MM-DD');
start = new Date(this.momentDate + ' 00:00');
end = new Date(this.momentDate + ' 23:59');
getcurrentUserPonto() {
const marcacoesCollection = this.afs.collection('contas')
.doc(this.globalService.contaId)
.collection('marcacoes', ref => ref
.where('datahora', '>', this.start)
.where('datahora', '<', this.end)).valueChanges()
return marcacoesCollection;
}
}
Obs: quando eu logo na aplicação funciona corretamente, mas quando eu já estou autenticado no main e dou um f5 o valor não vem, o valor de this.globalService.contaId vem como Undefined.
Estou usando angular e Firestore.