繁体   English   中英

无法访问来自另一个组件/ Angular 4中的auth.service的错误消息

[英]Cannot access error message from auth.service in another component/ Angular 4

在我的应用程序,我有auth.service ,我顺利拿到同时访问.then.catch在火力地堡方法signInWithEmailAndPassword 但是,然后我需要以某种方式访问​​另一个组件中的errorMsg变量,以根据此errorMsg带来的不同属性向用户显示错误消息。

但是,一旦尝试从另一个组件访问它,我总会得到以下信息:

' Cannot read property 'catch' of undefined' 

身份验证服务

  errorMsg: Promise<string>;
    signinUser(email: string, password: string) {
        firebase.auth().signInWithEmailAndPassword(email, password)
          .then(
            response => {
              this.router.navigate(['/movies']);
              firebase.auth().currentUser.getIdToken()
                .then(
                  (token: string) => this.token = token
                );
                this.getCurrentUser(firebase.auth().currentUser);
                this.isLogout = false;
            }
          )
          .catch(
            error => {
              this.errorMsg = error;
              console.log(this.errorMsg);
            }
          );
      }

登录组件

 errorMsg
onSignin(form: NgForm) {
    const email = form.value.email;
    const password = form.value.password;
    this.authService.signinUser(email, password);
    this.authService.errorMsg.catch(error => this.errorMsg = error);
  }

修改后的SignIn.Component.Ts

 get errorMsg(): string {
    this.errorAlert = this.authService.errorMsg;
    this.errorAlert !== '' ? this.errorAlert = this.errorAlert.replace('Error: ', '') : this.errorAlert = '';
    return this.authService.errorMsg;
  }

您可以尝试这样的事情:

身份验证服务

  errorMsg: string;   // Simple string

  signinUser(email: string, password: string) {
        firebase.auth().signInWithEmailAndPassword(email, password)
          .then(
            response => {
              this.router.navigate(['/movies']);
              firebase.auth().currentUser.getIdToken()
                .then(
                  (token: string) => this.token = token
                );
                this.getCurrentUser(firebase.auth().currentUser);
                this.isLogout = false;
            }
          )
          .catch(
            error => {
              this.errorMsg = error;
              console.log(this.errorMsg);
            }
          );
      }

登录组件

 get errorMsg(): string {
    return this.authService.errorMsg;
 ]

 onSignin(form: NgForm) {
    const email = form.value.email;
    const password = form.value.password;
    this.authService.signinUser(email, password);

  }

如果将errorMsg绑定在模板中,则类似的操作应该起作用。

Angular的内置更改检测功能会注意到更改,重新绑定并调用getter,该方法将始终从服务获取错误消息的当前值。

修改后的SignIn.Component.Ts

 get errorMsg(): string {
    this.errorAlert = this.authService.errorMsg;
    this.errorAlert = this.errorAlert ? this.errorAlert.replace('Error: ', '') : '';
    return this.errorAlert;
  }

暂无
暂无

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

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