首页 > 解决方案 > 具有 Firebase 身份验证的自定义用户名

问题描述

这里只是另一个 Angular 初学者。

我正在尝试制作一个应用程序,但我被困在 Firebase 用户身份验证部分。现在假设这个应用程序是关于一个名为“学生”的社区。所以这个应用程序的每个用户都是“学生”。

export interface Student {
  login : string,
  age : number,
  trainingsDone: number
}

另外,我的 SQL 数据库中有一个名为“students”的表示例:

login    | age | trainingsDone
"jeff3"  | 20  | 2
"paul23" | 21  | 3
...

现在,当您访问该应用程序时,您首先看到的是学生列表(在数据库中)。所以我只是展示它们,没什么特别的。为此,我在 AppComponent.ts 中添加了 getStudents() (使用 Http 请求)(见下文):

现在,身份验证部分。我知道这个过程可以在整个“身份验证服务”中完成,但让我们保持简单,并说一切都在 AppComponent 中完成。我已经导入了所有需要的东西,所以我的 AppComponent.ts 现在看起来像这样:

import { Component,  ChangeDetectionStrategy } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import firebase from 'firebase/app';
import { Student } from './data/Student';
import { Observable, of } from 'rxjs';
import { mergeMap, switchMap } from 'rxjs/operators';
import { AppUser } from './data/AppUser';

@Component({
  selector: 'app-root',
  template: `
    <div *ngIf="auth.user | async as user; else showLogin">
      <h1>Hello {{ user.displayName }}!</h1>
      <button (click)="logout()">Logout</button>
    </div>
    <ng-template #showLogin>
      <p>Please login.</p>
      <button (click)="login()">Login with Google</button>
    </ng-template>

    <table>
      <tr>
        <th>Login</th>
        <th>Age</th>
        <th>Trainings Done/th>
      </tr>
      <tr *ngFor="let student of students">
        <td>{{student.login}}</td>
        <td>{{student.age}}</td>
        <td>{{student.trainingsDone}}</td>
      </tr>
    </table>
  `,
})
export class AppComponent {
  students : Student[]; 
  constructor(public auth: AngularFireAuth, private http: HttpClient) {
  }

  getStudents(): Observable<Student[]>{
    return this.http.get<Student[]>("http://localhost:XXXX/api/students/").subscribe(data => this.students = data);
  }
  login() {
    this.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
  }
  logout() {
    this.auth.signOut();
  }
}

目前,我可以使用 Google 帐户登录和注销。我还可以在应用程序上看到学生表。一切正常,没有问题。

我想做的是链接到每个谷歌帐户,一个学生登录。所以我制作了一个名为“AppUser”的界面,将两者结合在一起:export interface AppUser { oAuth: AngularFireAuth, student: Student }

为此,我知道我应该使用“auth.user” Observable,一个 <Student | undefined> Observable,一个管道,和 mergeMap/switchMap 来做到这一点。然后另一个 Observable 用于更新:我们合并然后 combineLatest 创建 Observable<AppUser | 未定义>。但我不知道该怎么做。

有什么建议,提示吗?

标签: angulartypescriptfirebasespring-boot

解决方案


推荐阅读