尝试在函数内部设置某些内容时,未定义Angular Service类属性

时间:2017-05-01 04:06:41

标签: angular angular-services angular-components

我有一个带表格的注册页面。用户单击注册按钮,该按钮进入组件中的注册功能。组件中的寄存器功能进行2次调用:authService.register,然后是authService.verifyUser。

注册工作正常。但是,在verifyUser中,我一直收到一个错误,我的类属性(this.loggedInUser和this.userLoggedIn)在尝试设置它们时是未定义的。看起来有些东西搞砸了范围,但为什么我不能随时从任何函数设置类属性?

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.
    }
  });
  }
}

1 个答案:

答案 0 :(得分:1)

 var me = this;
 firebase.auth()....{
 me.loggedIn....
 }