Blake Rivell
Blake Rivell

Reputation: 13875

Angular Service class properties are undefined when trying to set something to them inside of a function

I have a registration page with a form. The user clicks a register button which goes to a register function in the component. The register function in the component makes 2 calls: authService.register and then authService.verifyUser.

Register is working fine. However, in verifyUser I keep getting an error that my class properties (this.loggedInUser and this.userLoggedIn) are undefined when trying to set something to them. It seems like something is messed up with the scope, but why wouldn't I be able to set class properties at any time from any function?

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

Upvotes: 1

Views: 916

Answers (1)

Rhea
Rhea

Reputation: 644

Do

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

Upvotes: 1

Related Questions