Angular 服务 class 属性在尝试在函数内部设置某些内容时未定义
Angular Service class properties are undefined when trying to set something to them inside of a function
我有一个带有表格的注册页面。用户单击注册按钮,该按钮将转到组件中的注册功能。组件中的注册函数进行了 2 次调用:authService.register 然后是 authService.verifyUser.
注册工作正常。但是,在 verifyUser 中,我不断收到错误消息,指出我的 class 属性(this.loggedInUser 和 this.userLoggedIn)在尝试为它们设置某些内容时未定义。似乎作用域出了问题,但为什么我不能随时从任何函数设置 class 属性?
export class AuthService {
userLoggedIn: boolean = false;
loggedInUser: string;
constructor(private router: Router) {}
register(email: string, password: string) {
firebase.auth().createUserWithEmailAndPassword(email, password)
.catch(function (error) {
alert(`${error.message} Please Try Again!`);
});
}
verifyUser() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
this.loggedInUser = user.email;
this.userLoggedIn = true;
this.router.navigate(['']);
} else {
// No user is signed in.
}
});
}
}
做
var me = this;
firebase.auth()....{
me.loggedIn....
}
我有一个带有表格的注册页面。用户单击注册按钮,该按钮将转到组件中的注册功能。组件中的注册函数进行了 2 次调用:authService.register 然后是 authService.verifyUser.
注册工作正常。但是,在 verifyUser 中,我不断收到错误消息,指出我的 class 属性(this.loggedInUser 和 this.userLoggedIn)在尝试为它们设置某些内容时未定义。似乎作用域出了问题,但为什么我不能随时从任何函数设置 class 属性?
export class AuthService {
userLoggedIn: boolean = false;
loggedInUser: string;
constructor(private router: Router) {}
register(email: string, password: string) {
firebase.auth().createUserWithEmailAndPassword(email, password)
.catch(function (error) {
alert(`${error.message} Please Try Again!`);
});
}
verifyUser() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
this.loggedInUser = user.email;
this.userLoggedIn = true;
this.router.navigate(['']);
} else {
// No user is signed in.
}
});
}
}
做
var me = this;
firebase.auth()....{
me.loggedIn....
}