【问题标题】:Angular 4 Firebase error message is not showing on first click第一次单击时未显示 Angular 4 Firebase 错误消息
【发布时间】:2017-11-19 21:28:43
【问题描述】:

我正在使用 Angular 4 进行 Firebase 身份验证。我正在尝试显示错误消息,但它在第二次单击时显示。在控制台中,它在第一次单击时显示错误,但是当我将它绑定到 HTML 组件时,它会在第二次单击时显示单击。我正在使用以下身份验证服务。

import { Injectable } from '@angular/core';
import { AngularFireDatabaseModule, AngularFireDatabase } from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
import { Router } from "@angular/router";
import * as firebase from 'firebase';

@Injectable()
export class AuthService {

  authState: any = null;
  isLoggedIn: any;
  error: any;

  constructor(private afAuth: AngularFireAuth,
              private db: AngularFireDatabase,
              private router:Router) {

            this.afAuth.authState.subscribe((auth) => {
              this.authState = auth
            });
          }

  // Returns true if user is logged in
  get authenticated(): boolean {
    return this.authState !== null;
  }

  // Returns current user data
  get currentUser(): any {
    return this.authenticated ? this.authState : null;
  }

  // Returns
  get currentUserObservable(): any {
    return this.afAuth.authState
  }

  // Returns current user UID
  get currentUserId(): string {
    return this.authenticated ? this.authState.uid : '';
  }
  emailLogin(email:string, password:string) {
     return this.afAuth.auth.signInWithEmailAndPassword(email, password)
       .then((user) => {
         this.router.navigate(['/dashboard_home'])
         this.isLoggedIn = this.authenticated;
       })
       .catch(error => {
        this.error = error;
        console.log(error)
      });
  }

  // Sends email allowing user to reset password
  resetPassword(email: string) {
    var auth = firebase.auth();

    return auth.sendPasswordResetEmail(email)
      .then(() => console.log("email sent"))
      .catch((error) => console.log(error))
  }


  //// Sign Out ////
  signOut(): void {
    this.afAuth.auth.signOut();
    this.router.navigate(['/administrator'])
  }

  //// Helpers ////
  private updateUserData(): void {
  // Writes user name and email to realtime db
  // useful if your app displays information about users or for admin features
    let path = `users/${this.currentUserId}`; // Endpoint on firebase
    let data = {
                  email: this.authState.email,
                  name: this.authState.displayName
                }

    this.db.object(path).update(data)
    .catch(error => console.log(error));

  }
}

我的 login.html 页面是这样的。

<div class="card-block">
   <div class="alert alert-danger" role="alert" *ngIf="error">{{ error }}</div>
   <form autocomplete="off" id="loginAdmin" (submit)="loginAdmin($event)">
      <div class="row">
         <div class="col-md-4 mx-auto">
            <mat-form-field>
               <input type="text" id="username" name="username" matInput placeholder="Användarnamn">
            </mat-form-field>
         </div>
      </div>
      <div class="row">
         <div class="col-md-4 mx-auto">
            <mat-form-field>
               <input type="password" id="password" name="password" matInput placeholder="Lösenord">
            </mat-form-field>
         </div>
      </div>
      <div class="row"></div>
      <div class="row">
         <div class="col-md-12 text-center">
            <button type="submit" mat-raised-button>Logga in</button>
         </div>
      </div>
   </form>
</div>

我的登录页面的 component.ts 已给出

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../services/auth/auth.service';
import {Router} from "@angular/router";
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  error = '';

  constructor(private authService: AuthService, private router: Router) { }
  ngOnInit() {
  }

  loginAdmin(e) {
    e.preventDefault();
    var email = e.target.elements[0].value;
    var password = e.target.elements[1].value;
    if(email && password) {
      var responses = this.authService.emailLogin(email, password);
      this.error = this.authService.error;
    }

  }
}

如果您使用上述服务,您可以登录使用。但如果电子邮件和密码不正确,它会在控制台中显示错误,并且在与 HTML 绑定时不会显示。 装订是这样的。

<div class="alert alert-danger" role="alert" *ngIf="error">{{ error }}</div>

现在我想要的是,在第一次点击时发送显示错误以及登录所有用户数据。

【问题讨论】:

    标签: javascript angular firebase firebase-realtime-database angular4-forms


    【解决方案1】:

    我喜欢这个解决方案。这项服务对我有用。

    import {AngularFireAuth} from 'angularfire2/auth';
    
    @Injectable()
    export class AuthService {
    
      authState: any = null;
    
      constructor(private afAuth: AngularFireAuth, private router: Router) {
        this.afAuth.authState.subscribe((auth) => {
          this.authState = auth
        });
      }
    
      get isUserAnonymousLoggedIn(): boolean {
        return (this.authState !== null) ? this.authState.isAnonymous : false
      }
    
      get currentUserId(): string {
        return (this.authState !== null) ? this.authState.uid : ''
      }
    
      get currentUserName(): string {
        return this.authState['email']
      }
    
      get currentUser(): any {
        return (this.authState !== null) ? this.authState : null;
      }
    
      get isUserEmailLoggedIn(): boolean {
        if ((this.authState !== null) && (!this.isUserAnonymousLoggedIn)) {
          return true
        } else {
          return false
        }
      }
    
      signUpWithEmail(email: string, password: string) {
        return this.afAuth.auth.createUserWithEmailAndPassword(email, password)
          .then((user) => {
            this.authState = user
          })
          .catch(error => {
            console.log(error)
            throw error
          });
      }
    
      loginWithEmail(email: string, password: string) {
        return this.afAuth.auth.signInWithEmailAndPassword(email, password)
          .then((user) => {
            this.authState = user
          })
          .catch(error => {
            console.log(error)
            throw error
          });
      }
    
      signOut(): void {
        this.afAuth.auth.signOut();
        this.router.navigate(['/'])
      }
    }
    

    更多详情请访问Angular 4 Firebase Auth – Email/Password Authentication with AngularFire2 v4

    【讨论】:

    • 嗨,您是如何更改组件和视图以实际显示您在 AuthService 中抛出的错误的?
    • 这是我近三天面临的问题。按照这个链接帮助我解决这个问题。 javasampleapproach.com/frontend/angular/…
    • 在你的视野中过去...

      0" class="alert alert-danger"> {{errorMessage}}

      0" class="alert alert-danger"> {{error.message}}

    • 检查用户是否登录
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 2012-09-02
    • 1970-01-01
    相关资源
    最近更新 更多