【问题标题】:Angular Service Variable comes up as undefined in componentAngular 服务变量在组件中未定义
【发布时间】:2020-11-27 19:28:57
【问题描述】:

我有一个使用 firebase 电子邮件/密码身份验证登录的应用,如果用户登录失败,我希望能够向用户显示 firebase 身份验证错误。

我已经进入了我的 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;

      });
  }

但是当我将 AuthError 分配给登录组件中的另一个变量以向用户显示时,它会显示为未定义。

这是我的登录组件中的一个部分.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

当用户登录失败时控制台显示:

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

由于某种原因,this.authService.AuthError 在登录组件中未定义,而我希望它在 AuthService 中显示与 err.message 相同的消息。

提前致谢,如果需要任何其他信息,请告诉我。

【问题讨论】:

  • errorMessage 未定义,因为您甚至在服务器发送响应之前就在检查它的值。
  • 服务器发送响应后如何查看值?

标签: angular typescript firebase-authentication


【解决方案1】:

试试下面的。 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

【讨论】:

    猜你喜欢
    • 2018-11-16
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    相关资源
    最近更新 更多