我正在尝试获取当前用户,并希望将用户值设置为getter。在构造函数中,我可以看到控制台正在返回已验证为true的电子邮件,但是当我尝试将其设置为getter时,它将显示无法读取未定义的属性'emailVerified'。请在下面找到我的代码。
import { Injectable } from "@angular/core";
import { AngularFireAuth } from "@angular/fire/auth";
import * as firebase from "firebase/app";
//import 'rxjs/add/operator/toPromise';
@Injectable({
providedIn: "root"
})
export class AuthService {
userData: any; // Save logged in user data
constructor(public afAuth: AngularFireAuth) {
/* logged in and setting up null when logged out */
this.afAuth.authState.subscribe(user => {
if (user) {
this.userData = user;
console.log(this.userData, this.userData.emailVerified)
} else {
this.userData = null;
}
})
}
// Returns true when user is looged in and email is verified
get isLoggedIn(): boolean {
const user = this.userData;
return ( user !== null && user.emailVerified !== false ) ? true : false;
}
}
答案 0 :(得分:0)
在用户登录并验证电子邮件后返回true:
get isLoggedIn(): boolean {
const user = this.userData;
if(user === null || user === undefined) return false
return user.emailVerified;
}
答案 1 :(得分:0)
与常规函数不同,箭头函数没有自己的this
,这是因为您无法访问 emailVerified 键并给您类似Cannot read property 'emailVerified' of undefined
请检查此代码,然后重试:
/* logged in and setting up null when logged out */
this.afAuth.authState.subscribe( function(user) {
if (user) {
this.userData = user;
console.log(this.userData, this.userData.emailVerified)
} else {
this.userData = null;
}
})
我认为这会起作用