我已经使用Google搜索了几天,并尝试了许多不同的操作,但是我无法从用户集合中将用户数据从服务中获取到我的component.ts文件中,以预先填充formbuilder表单。这是下面的服务代码和我的组件打字稿文件。我可以使用* ngIf =“ auth.user | async作为用户在组件模板中获取用户数据,但不能在组件打字稿文件中获取它。
// 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);
}
}
}
所以我如何从当前用户集合中获取用户unitNumber并预填充formBuilder unitNumber字段和其他字段。
谢谢!
所以解决方案是: