【问题标题】:Angular and Firebase: display error message to userAngular 和 Firebase:向用户显示错误消息
【发布时间】:2020-03-18 00:30:17
【问题描述】:

所以我对 Angular JS、html 和 css 还是很陌生。当用户单击提交按钮时,它应该路由到登录页面或返回登录页面并显示和错误消息,例如“无法识别提供的密码和电子邮件组合”。我是否必须调用 firebase 来获取用户的密码并将其与提交时输入表单中密码字段的任何内容进行比较?

我为注册做了类似的事情,但都是在 html 中比较密码和确认密码以查看它们是否匹配,但我认为我的请求不能全部在 login-component.html 中。

login.component.html

<div class="form centerForm">
<h1>Login</h1>
<form [formGroup]="login" (ngSubmit)="onLogin(login)">
    <div class="row">
        <div class="radio">
            <label>
                <input type="radio" name="user" formControlName="user" value='parent'>Parent
            </label>
        </div>
        <div class="radio">
            <label>
                <input type="radio" name="user" formControlName="user" value='child'>Child
            </label>
        </div>
    </div>

    <div class="form-group">
        <label>Email: </label>
        <input placeholder="john.doe@email.com"
               formControlName="email"
               required>
        <br>
        <label>Password: </label>
        <input type="password"
               placeholder="password"
               formControlName="password"
               required>
        <br>

    </div>
    <button type="submit" class="btn btn-primary">Login</button>
</form>

login.component.ts

import { Component, OnInit } from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import { AuthService } from 'src/app/services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {


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

  login = new FormGroup({
    user: new FormControl('', [Validators.required]),
    email : new FormControl('',
        [Validators.required, Validators.email]),
    password : new FormControl('',
        [Validators.required])
  });


  get email() {
    return this.login.get('email');
  }

  get user() {
    return this.login.get('user');
  }

  get password() {
    return this.login.get('password');
  }


  onLogin(form) {
    const email = form.value.email;
    const password = form.value.password;
    const user= form.value.user;
    this.authService.login(email, password, user);
    }



  ngOnInit() {
  }

}

auth.service.ts

import { Injectable } from '@angular/core';
import * as firebase from 'firebase';
import { Router } from '@angular/router';
import { ChildService } from './child.service';
import { ParentService } from './parent.service';
import { PointsService } from './points.service';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  token;



  user= 'child';
  uid;

  constructor(private router: Router,
              private childService: ChildService,
              private parentService: ParentService,
              private pointsService: PointsService) {
  }

  signUpParent(email: string, password: string){
    firebase.auth().createUserWithEmailAndPassword(email, password)
    .then(
      response => {
        firebase.auth().currentUser.getIdToken().then(
          (token: string) => {
              this.token = token;
                this.uid = firebase.auth().currentUser.uid;
                this.user='parent';
                console.log(this.uid)
          }).then( 
            response =>{
              this.parentService.addParent(email, this.uid);
              this.router.navigate(['home']);
            })
          .catch(
          error => {
            console.log(error);
            alert(error)
          });
        });
      }

      signUpChild(email: string, password: string, parentID:string, name: string){
        firebase.auth().createUserWithEmailAndPassword(email, password)
        .then(
          response => {
            firebase.auth().currentUser.getIdToken().then(
              (token: string) => {
                  this.token = token;
                    this.uid = firebase.auth().currentUser.uid;
                    this.user='child';
                    console.log(this.uid)
              }).then( 
                response =>{
                  this.childService.addChild(parentID, name, this.uid);
                  this.pointsService.addtoPointsDB(this.uid); 
                  this.router.navigate(['child-chores']);
                })
              .catch(
              error => {console.log(error);
              })
            });
          }

  login(email: string, password: string, user: string) {
    firebase.auth().signInWithEmailAndPassword(email, password)
        .then(
            response => {
                firebase.auth().currentUser.getIdToken().then(
                    (token: string) => {
                        this.token = token;
                        this.uid = firebase.auth().currentUser.uid;
                        this.user= user;
                        if(user=='parent'){
                          this.parentService.setParentID(firebase.auth().currentUser.uid);}
                        else {
                          this.childService.setChildID(firebase.auth().currentUser.uid)
                        }
                    })
                    .then(response => {
                      if(this.user=='child'){
                        this.router.navigate(['child-chores']);
                      }
                      else{
                        this.router.navigate(['home']);}
                      }).catch(
                    error => {console.log(error);
                    });
            });
}

logout() {
    firebase.auth().signOut().then(() => console.log('logged you out')).catch(
        error => console.log(error)
    );
    this.token = null;
    this.childService.setChildNameIDPoints(null,null, null, null);
    this.router.navigate(['']);
}

isAuthenticated() {
  return this.token != null;
}


}

【问题讨论】:

    标签: javascript html angular typescript firebase


    【解决方案1】:

    您需要使用用户输入的电子邮件+密码调用 Firebase 身份验证的 firebase.auth().signInWithEmailAndPassword(email, password) API。

    如果失败了,你告诉他们再试一次

    【讨论】:

    • 我会在哪里打这个电话?在我的 ts 中的 onLogin 函数中?
    【解决方案2】:

    我认为这可能会有所帮助:

    auth.service;

        async loginByEmailAndPassword(email: string, password: string, user: string) {
            await firebase.auth().signInWithEmailAndPassword(email, password).then((user) => {
                  firebase.auth().updateCurrentUser(firebase.auth().currentUser);
    
                if (user === 'parent') {
                     this.parentService.setParentID(firebase.auth().currentUser.uid);
                }
                else {
                     this.childService.setChildID(firebase.auth().currentUser.uid)
                }
         });
    }
    

    登录组件;

      async loginByEmailAndPassword(values) {
          this.accountErrorMessage = "";
    
          await this.authService.loginByEmailAndPassword(email, password)
             .then(() => {
                if (this.user == 'child') {
                    this.router.navigate(['child-chores']);
                }
                else {
                    this.router.navigate(['home']);
                }
          })
          .catch((error) => {
              switch (error.code) {
                case "auth/invalid-email":
                case "auth/wrong-password":
                case "auth/user-not-found":
                {
                   this.accountErrorMessage = "Wrong email address or password.";
                   break;
                }
                   default:
                {
                    this.accountErrorMessage = "Unexpected Error";
                    break;
                }
           }
      });
    

    并将其添加到 html 以显示错误;

    <div *ngIf="accountErrorMessage">{{ accountErrorMessage }}</div>
    

    另外,也许您想使用最新的 AngularFire 插件,我认为它有时可以更轻松地使用 firebase 功能。尤其是路由器守卫。

    【讨论】:

    • 你从哪里得到 afAuth 中的“af”?
    • 啊抱歉,我忘记更改那部分了。我正在使用 angularFire 插件,所以我将它作为 afAuth 导入。我将编辑“* as firebase”的答案
    猜你喜欢
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多