首页 > 解决方案 > 无需身份验证即可从实时 Firebase 数据库登录

问题描述

请帮助我从 Realtime firebase 数据库登录而无需身份验证。我想获取密钥并将密码与用户输入的密码进行比较。

我附上了一些代码,请检查我。

登录组件.html

<div class="form-group">
                <input type="text" id="empid" [(ngModel)]="empid" class="form-control m-2" placeholder="Employee Id">
            </div>
            <div class="form-group" *ngIf="!isForgotPassword">
                <input type="password" class="form-control m-2" [(ngModel)]="passwordInput" placeholder="Password" id="password">
            </div>
            <div class="form-group" *ngIf="!isForgotPassword">
            <span *ngIf="selectedVal == 'login'; else elseBlock">
                <button type="button" class="btn btn-orange btn-block m-2" (click)="loginUser()">Login</button>
            </span>

登录组件.ts

 emailInput: string;
 passwordInput: string;
 isForgotPassword: boolean;
 empId : string;
 userDetails: any;

constructor(
 private userService: UserService,
 private router: Router
) {
 this.selectedVal = 'login';
 this.isForgotPassword = false;
}

loginUser(){
  this.userService.login(this.empId, this.passwordInput);
}

用户服务.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase} from 'angularfire2/database';
import { User } from '../user.model'
import { Router } from '@angular/router';
import * as firebase from 'firebase';

@Injectable({
  providedIn: 'root'
  })
 export class UserService {
  user : User[];
  ref = 'Batch'
  batch = 'DEC2019'

  constructor(
     public af: AngularFireDatabase,
     public router: Router
  ) { }

  login(empId: string, password: string){
     return this.af.database.ref('Users/').child(empId).once('value')
    .then(snapshot=>{ 

   })
   .catch(err =>{
     console.log('Something went wrong',err.message)
   })
 }

标签: javascripttypescriptfirebasefirebase-realtime-databaseangular8

解决方案


您正在使用 angularfire,您可以在服务类中执行以下操作:

items: Observable<any[]>;
...

 login(empId: string){
     return this.itemRef = db.object('item/' + empId).snapshotChanges();
 }

然后在组件中,您subscribe可以observable

loginUser(){
  this.userService.login(this.empId).subscribe(action => {
  console.log(action.type);
  console.log(action.key)
  console.log(action.payload.val())
 });
}

action.payload.val()action.payload.val().password将包含您的数据,如果您password在数据库中有一个属性,您可能可以通过这样做来检索密码。然后您可以检查检索到的密码是否与passwordInput. 您可能应该使用它,reactive-form因为您可以轻松地validation使用它:

https://angular.io/guide/reactive-forms#simple-form-validation

https://github.com/angular/angularfire/blob/master/docs/rtdb/objects.md


推荐阅读