Я пытаюсь проверить, является ли authService.userData как пользователь для проверки электронной почты для проверки подлинности, он просто возвращает свойство неопределенным, и я не понимаю, почему. Может быть, мои знания в angular отсутствуют, но я нигде не могу найти объяснения этому. Это мой auth.service.ts
import { Injectable, NgZone } from '@angular/core';
import { User } from "../service/user";
import { auth } from 'firebase/app';
import { AngularFireAuth } from "@angular/fire/auth";
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Router } from "@angular/router";
@Injectable({
providedIn: 'root'
})
export class AuthService {
userData: any; // Save logged in user data
constructor(
public afs: AngularFirestore, // Inject Firestore service
public afAuth: AngularFireAuth, // Inject Firebase auth service
public router: Router,
public ngZone: NgZone // NgZone service to remove outside scope warning
) {
/* Saving user data in localstorage when
logged in and setting up null when logged out */
this.afAuth.authState.subscribe(user => {
if (user) {
this.userData = user;
localStorage.setItem('user', JSON.stringify(this.userData));
JSON.parse(localStorage.getItem('user'));
} else {
localStorage.setItem('user', null);
JSON.parse(localStorage.getItem('user'));
}
})
}
// Sign in with email/password
SignIn(email, password) {
return this.afAuth.auth.signInWithEmailAndPassword(email, password)
.then((result) => {
this.ngZone.run(() => {
this.router.navigate(['dashboard']);
});
this.SetUserData(result.user);
}).catch((error) => {
window.alert(error.message)
})
}
// Sign up with email/password
SignUp(email, password) {
return this.afAuth.auth.createUserWithEmailAndPassword(email, password)
.then((result) => {
/* Call the SendVerificaitonMail() function when new user sign
up and returns promise */
this.SendVerificationMail();
this.SetUserData(result.user);
}).catch((error) => {
window.alert(error.message)
})
}
// Send email verfificaiton when new user sign up
SendVerificationMail() {
return this.afAuth.auth.currentUser.sendEmailVerification()
.then(() => {
this.router.navigate(['verify-email']);
})
}
// Reset Forggot password
ForgotPassword(passwordResetEmail) {
return this.afAuth.auth.sendPasswordResetEmail(passwordResetEmail)
.then(() => {
window.alert('Password reset email sent, check your inbox.');
}).catch((error) => {
window.alert(error)
})
}
// Returns true when user is looged in and email is verified
get isLoggedIn(): boolean {
const user = JSON.parse(localStorage.getItem('user'));
return (user !== null && user.emailVerified !== false) ? true : false;
}
// Sign in with Google
GoogleAuth() {
return this.AuthLogin(new auth.GoogleAuthProvider());
}
// Auth logic to run auth providers
AuthLogin(provider) {
return this.afAuth.auth.signInWithPopup(provider)
.then((result) => {
this.ngZone.run(() => {
this.router.navigate(['dashboard']);
})
this.SetUserData(result.user);
}).catch((error) => {
window.alert(error)
})
}
/* Setting up user data when sign in with username/password,
sign up with username/password and sign in with social auth
provider in Firestore database using AngularFirestore + AngularFirestoreDocument service */
SetUserData(user) {
const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.uid}`);
const userData: User = {
uid: user.uid,
email: user.email,
displayName: user.displayName,
photoURL: user.photoURL,
emailVerified: user.emailVerified
}
return userRef.set(userData, {
merge: true
})
}
// Sign out
SignOut() {
return this.afAuth.auth.signOut().then(() => {
localStorage.removeItem('user');
this.router.navigate(['sign-in']);
})
}
}
Это компонент, в котором я получаю сообщение об ошибке.
verify-email.component. html
<div class="displayTable">
<div class="displayTableCell">
<div class="authBlock">
<h3>Thank You for Registering</h3>
<div class="formGroup" *ngIf="authService.userData as user">
<p class="text-center">We have sent a confirmation email to <strong>{{user.email}}</strong>.</p>
<p class="text-center">Please check your email and click on the link to verfiy your email address.</p>
</div>
<!-- Calling SendVerificationMail() method using authService Api -->
<div class="formGroup">
<button type="button" class="btn btnPrimary" (click)="authService.SendVerificationMail()">
<i class="fas fa-redo-alt"></i>
Resend Verification Email
</button>
</div>
</div>
<div class="redirectToLogin">
<span>Go back to?<span class="redirect" routerLink="/sign-in"> Sign in</span></span>
</div>
</div>
</div>
Это ошибка, которую я получаю
verify-email.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../service/auth.service';
@Component({
selector: 'app-verify-email',
templateUrl: './verify-email.component.html',
styleUrls: ['./verify-email.component.css']
})
export class VerifyEmailComponent implements OnInit {
constructor( public authservice: AuthService) { }
ngOnInit() {
}
}