TypeError:无法读取角度中未定义的属性'userData'

问题描述 投票:0回答:1

我正在尝试检查authService.userData是否作为用于验证电子邮件以进行身份​​验证的用户,它只是返回未定义的属性,我不明白为什么。也许我缺乏角度方面的知识,但是我在任何地方都找不到这种解释。这是我的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>

这是我得到的错误

enter image description here

angular firebase firebase-authentication forms-authentication angular-services
1个回答
0
投票

VerifyEmailComponent.html:7中,您可以添加如下所示的Elvis运算符:*ngIf="authService?.userData as user"。它将解决问题或使您离起点更近。

© www.soinside.com 2019 - 2024. All rights reserved.