简体   繁体   English

Angular 服务变量在组件中出现未定义

[英]Angular Service Variable comes up as undefined in component

I have an app that uses firebase email/password auth to login and I want to be able to display firebase auth errors to the user if they fail login.我有一个应用程序使用 firebase 电子邮件/密码身份验证登录,我希望能够在登录失败时向用户显示 firebase 身份验证错误。

Ive got in my AuthService:我已经进入了我的 AuthService:

AuthError: string;


  login(email: string, password: string) {
    this.firebaseAuth
      .signInWithEmailAndPassword(email, password)
      .then(value => {
        console.log('Nice, it worked!');
        this.navroute.navigate(['home']);
        
      })
      .catch(err => {
        console.log('Something went wrong:',err.message);
        this.AuthError = err.message;

      });
  }

But when I assign AuthError to anther variable in my login component to display to the user it comes up as undefined.但是,当我将 AuthError 分配给登录组件中的另一个变量以显示给用户时,它会显示为未定义。

Here is a section from my login component.ts这是我的登录 component.ts 中的一部分

errorMessage: string;

submit(){
    console.log("login");
    this.email = this.LoginForm.value.inputUsername;
    this.password = this.LoginForm.value.inputPassword;

    if(this.email ==  null || this.password == null){
      this.errorMessage = "Username or password cannot be empty!";
    } else{
      this.authService.login(this.email, this.password);
      this.LoginForm.reset();
      console.log(this.authService.AuthError);
    }
  }//end submit

and the console when a user fails login shows:用户登录失败时的控制台显示:

login
undefined
auth.service.ts:48 Something went wrong: The email address is badly formatted.

for some reason, this.authService.AuthError is undefined in the login component, when instead what I'd like for it to do is show the same message as err.message in the AuthService.由于某种原因,this.authService.AuthError 在登录组件中未定义,而我希望它在 AuthService 中显示与 err.message 相同的消息。

Thanks in advance and please let me know if any additional info is needed.提前致谢,如果需要任何其他信息,请告诉我。

Try the below.试试下面的。 The value in this.authService.AuthError only be available after the login, right? this.authService.AuthError 中的值只有在登录后才可用,对吗?

  submit(){
        console.log("login");
        this.email = this.LoginForm.value.inputUsername;
        this.password = this.LoginForm.value.inputPassword;
    
        if(this.email ==  null || this.password == null){
          this.errorMessage = "Username or password cannot be empty!";
        } else{
    
          this.authService.login(this.email, this.password).subscribe(data= {
    
     console.log(this.authService.AuthError);
    });
         
         
        }
      }//

end submit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM