I've been Googling for days now and tried many different things and I'm unable to get the user data from the user collection from my service to my component.ts file to pre-populate my formbuilder form. Here is the service code below and my component typescript file. I can get user data in the template of the component using *ngIf="auth.user | async as user but I can't get it in the component typescript file.
// auth.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Observable, of } from 'rxjs';
import { first, switchMap } from 'rxjs/operators';
export interface User {
uid: string;
displayName: string;
email: string;
photoURL: string;
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
user: Observable<User>;
requesting = false;
response: any;
constructor(public afAuth: AngularFireAuth,
private afs: AngularFirestore,
private router: Router) {
this.user = this.afAuth.authState.pipe(
switchMap(user => {
if (user) {
sessionStorage.setItem('user', JSON.stringify(user));
return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
} else {
return of(null);
}
}));
}
async userLogin(email: string, password: string) {
this.requesting = true;
this.afAuth
.auth
.signInWithEmailAndPassword(email, password)
.then(user => {
sessionStorage.setItem('user', JSON.stringify(user.user));
this.router.navigate(['/dashboard']);
this.requesting = false;
})
.catch(err => {
this.requesting = false;
this.response = err.message;
console.log('Something went wrong:', err.message);
});
}
async logout() {
this.afAuth.auth.signOut().then(() => {
sessionStorage.removeItem('user');
this.router.navigate(['/']);
});
}
get isLoggedIn(): boolean {
const user = JSON.parse(sessionStorage.getItem('user'));
return user !== null;
}
}
// profile-page.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AuthService } from '@services/auth.service';
import { AngularFireAuth } from '@angular/fire/auth';
@Component({
selector: 'app-profile-page',
templateUrl: './profile-page.component.html',
styleUrls: ['./profile-page.component.scss'],
providers: [AuthService]
})
export class ProfilePageComponent implements OnInit {
profileData: FormGroup;
formSubmitted = false;
user: any;
constructor(public auth: AuthService, private fb: FormBuilder, public afAuth: AngularFireAuth) {
}
ngOnInit() {
this.profileData = this.fb.group({
unitNumber: ['', [Validators.required]],
displayName: ['', [Validators.required]],
lastName: ['', [Validators.required]],
tagNumber: ['', [Validators.required]],
email: ['', [Validators.required, Validators.pattern('[a-zA-Z0-9.-]{1,}@[a-zA-Z0-9.-]{2,}[.]{1}[a-zA-Z]{2,}')]],
contactNumber: ['', [Validators.required]],
});
}
onSubmit(): void {
this.formSubmitted = true;
if (this.profileData.dirty && this.profileData.valid) {
console.log(this.profileData.value);
}
}
}
So how would I get the user unitNumber from the current user collection and pre-populate the formBuilder unitNumber field and other fields.
Thank you!
So the solution to this is:
import { AngularFirestore } from '@angular/fire/firestore';
export class Whatever {
currentUser: any;
constructor(private db: AngularFirestore) {}
this.db.collection('users').doc('some_uid').valueChanges().subscribe((response) => {
this.currentUser = response;
});
}
Then you can get the current user values and pop it into the form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With