Currently, I'm working on an Angular service that leverages AngularFire's auth observable to monitor user state changes. Upon a user signing in, the application should retrieve a user document from MongoDB. To enable components to consume this data, I need to establish another observable. However, I'm encountering difficulties figuring out how to achieve this.
Displayed below is a snippet of my auth service:
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { Router } from '@angular/router';
import firebase from 'firebase/app';
import { environment } from '../../environments/environment'
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { User } from '../interfaces/User.model'
@Injectable({
providedIn: 'root'
})
export class AuthService {
public redirectRoute = ''
public loginError = '';
public _mongoUser: Observable<User | null> = of(null);
public mongoUser: User | null = null;
constructor(public auth: AngularFireAuth, private router: Router, private http: HttpClient,) {
this.auth.user.subscribe(async (user) => {
console.log('auth changed', user)
if (user) {
let headers = {
headers: new HttpHeaders()
.set('idToken', await user.getIdToken())
}
this._mongoUser = this.http.post<User>(
`${environment.apiUrl}/users/email/${user.email}`,
{ personal: { email: user.email } },
headers
)
this._mongoUser.subscribe(val => {
console.log('val', val)
this.mongoUser = val
})
} else {
}
})
}
}
My main dilemma revolves around the initialization of _mongoUser. The current method using 'of' and the httpClient approach is not yielding the desired outcome.
My objective is to utilize _mongoUser or mongoUser in other components, however, the existing code does not suffice. Here's an example:
constructor() {
this.authService._mongoUser.subscribe(val => {
if (val) {
this.editForm.patchValue({ 'username': val.username })
}
})
}