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

问题描述 投票:0回答:1

在我的应用程序中,我有auth.service,我成功访问Firebase .then上的.catchsignInWithEmailAndPassword方法。但是,我需要以某种方式在另一个组件中访问此errorMsg变量,以根据此errorMsg带来的不同属性向用户显示错误消息。

但是,一旦我尝试从另一个组件访问它,我总是得到这个:

' Cannot read property 'catch' of undefined' 

Auth.Service.Ts

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

SignIn.Component.Ts

 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;
  }
angular error-handling promise firebase-authentication
1个回答
0
投票

你可以尝试这样的事情:

Auth.Service.Ts

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

SignIn.Component.Ts

 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;
  }
© www.soinside.com 2019 - 2024. All rights reserved.