【问题标题】:Angular6 Firebase Authentication with Email and Password使用电子邮件和密码进行 Angular6 Firebase 身份验证
【发布时间】:2018-09-29 20:20:48
【问题描述】:

请帮助我,我是 angular6 firebase 编程的新手。 我有很好的带有电子邮件和密码的 Firebase 身份验证系统。但是从注册开始,当我将用户存储在数据库中时,我只能获得 uid 和电子邮件。我对 updateProfile 很感兴趣,但不知道如何在我的代码中实现。 我正在使用“@angular/fire”:“^5.0.0”, "firebase": "^5.5.1", 所以我问这个版本好还是我需要改变。 回到问题:服务:

 import { Injectable } from "@angular/core";
    import { AngularFireAuth } from "@angular/fire/auth";
    import {
      AngularFirestore,
      AngularFirestoreCollection,
      AngularFirestoreDocument
    } from "@angular/fire/firestore";
    import { Observable } from "rxjs";
    import "rxjs/add/operator/map";

    @Injectable()
    export class AuthService {
      constructor(private afAuth: AngularFireAuth, private db: AngularFirestore) {
        // this.afAuth.authState.subscribe(auth => console.log(auth));
      }

      login(email: string, password: string) {
        return new Promise((resolove, reject) => {
          this.afAuth.auth
            .signInWithEmailAndPassword(email, password)
            .then(userData => resolove(userData), err => reject(err));
        });
      }
      getAuth() {
        return this.afAuth.authState.map(auth => auth);
      }
      logout() {
        this.afAuth.auth.signOut();
      }
      register(email: string, password: string) {
        return new Promise((resolove, reject) => {
          this.afAuth.auth
            .createUserWithEmailAndPassword(email, password)
            .then(userData => resolove(userData), err => reject(err));
        });
      }
    }

组件

import { Component, OnInit } from "@angular/core";
import { AuthService } from "../../service/auth.service";
import { Router } from "@angular/router";

@Component({
  selector: "app-register",
  templateUrl: "./register.component.html",
  styleUrls: ["./register.component.css"]
})
export class RegisterComponent implements OnInit {
  email: string;
  password: string;
  constructor(private authService: AuthService, private router: Router) {}

  ngOnInit() {}

  onSubmit() {
    this.authService
      .register(this.email, this.password)
      .then(res => {
        this.router.navigate(["/"]);
      })
      .catch(err => console.log(err.message));
  }
}

我的目标是在数据库中将 displayName 和 Skill 作为 User 的属性。使用我的代码注册后 displayName 为空。所以我的问题是如何将 displayName 存储在数据库中? 泰 维克多。

【问题讨论】:

  • 欢迎来到 StackOverflow。我不确定你的问题是什么。
  • 我正在使用 Firebase 电子邮件和密码身份验证。它有效。但我也想将 displayName 道具存储在数据库中。例如,我想说你好 {{ user.displayName }}。但我不能因为我不知道如何将它存储在数据库中。 Atm displayName 为空。
  • 你使用的是firestore还是实时数据库?
  • 云火存储。

标签: typescript firebase firebase-authentication angular6 angularfire2


【解决方案1】:

欢迎来到 StackOverflow。

displayName 之所以为空,是因为它默认为空(除非您从 Facebook 和 Google 等社交网络登录)。你应该考虑做的是:

  • 在每次注册时,在 users 集合中创建一个新文档(将其命名为您想要的任何名称)。
  • 每次登录时,更新用户的现有文档(您不必这样做,但有时它很有用)。
  • 根据当前认证用户获取用户文档。

让我们从注册开始:

您有多种登录方法,但我将向您解释如何通过电子邮件/密码完成。

首先,我们需要创建接受电子邮件和密码参数的方法register。我看到您已经创建了该方法,但您应该知道您不需要在 Promise 中限定createUserWithEmailAndPassword,因为它已经是一个 Promise。用户注册后,我们会将他的数据添加到我们的集合中:

register(email: string, password: string) {
  this.afAuth.auth.createUserWithEmailAndPassword(email, password)
    .then(userCredential => this.upsertUserData(userCredential))
    .catch(error => this.handleAuthError(error);
}

private upsertUserData(userCredential: firebase.auth.UserCredential) {
  // Upsert = Update/Insert.
  return this.afs.doc(`users/${userCredential.uid}`).update({
    email: userCredential.email
  });
}

private handleAuthError(error) {
  console.error(error)
}

如您所见,我创建了另外两个方法,以使方法 register 更加简洁易读。

现在我们已经注册完成了,让我们来做登录方法,几乎​​一样:

login(email: string, password: string) {
  this.afAuth.signInWithEmailAndPassword(email, password)
    .then(userCredential => this.upsertUserData(userCredential))
    .catch(error = > this.handleAuthError(error));
}

在我们注册并登录应用程序后,我们想获取用户的数据,以便我们可以这样做:

export class AuthService {

...

user$: Observable<{displayName: string, email: string}> = this.afAuth.authState.pipe(
  switchMap(user => Boolean(user) ? this.afs.doc(`users/${user.id}`).valueChanges() : of(null))
);

...
}

简单地说-this.afAuth.authState 将在用户登录时发出一个对象。如果用户未登录,将返回一个空值。 user$会在用户登录时返回用户的文档数据。如果用户不存在(即authState = null),则返回null。

【讨论】:

  • 我的代码现在看起来和你的一样。但我有这个错误:node_modules/@angular/fire/firebase.app.module.d.ts(17,22) 中的错误:错误 TS2420:“FirebaseApp”类错误地实现了“App”接口。属性“消息”的类型不兼容。类型“() => Messaging”不可分配给类型“MessagingFactory”。类型“() => 消息传递”中缺少属性“isSupported”。 node_modules/@firebase/auth-types/index.d.ts(271,21):错误 TS2314:通用类型 'Observer' 需要 1 个类型参数。 node_modules/@firebase/auth-types/index.d.ts(276,21):错误 TS2314:
  • 我从 "firebase": "^5.5.1" 移动到 "firebase": "^5.0.0" 因为我不能在那个版本中使用 firebase.auth,不知道为什么,它只是说找不到火力基地/应用程序
  • 你需要像import { auth } from 'firebase/app'一样导入认证
  • 并导入 firebase - import * as firebase from 'firebase/app'
猜你喜欢
  • 2019-06-11
  • 1970-01-01
  • 2018-09-03
  • 2014-01-17
  • 1970-01-01
  • 2016-12-13
  • 2019-03-15
  • 2016-11-13
相关资源
最近更新 更多