Angular 9 + Firebase (2) : Firebase Authentication 做個 Google 登入應用


本文為 AngularFire 介紹,改寫自 AngularFire 官方文件

目標:
做一個 google 登入按鈕,使用 Firebase Authentication 處理身分驗證。AuthService 處理用戶登入、登出(與用戶資料 CRUD)。

step 1. 建立 AuthService
step 2. 將 AuthService 注入 Component
step 3. 獲取用戶資料

步驟

step 1. 建立 AuthService

建立 service,import AngularFireAuth、auth
將登入資訊用存在 LocalStorage
authState() return this.auth.authState

auth.service.ts

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { auth } from 'firebase/app';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  public userData: any; // Save logged in user data

  constructor(
    public auth: AngularFireAuth
  ) {
    /* Saving user data in localstorage when
    logged in and setting up null when logged out */
    this.auth.authState.subscribe(user => {
      if (user) {
        this.userData = user;
        localStorage.setItem('user', JSON.stringify(this.userData));
        JSON.parse(localStorage.getItem('user'));
      } else {
        localStorage.setItem('user', null);
        JSON.parse(localStorage.getItem('user'));
      }
    })
  }

  async login() {
    this.auth.signInWithPopup(new auth.GoogleAuthProvider());
  }
  logout() {
    this.auth.signOut();
    window.location.reload();
  }

  get authState(): Observable<any> {
    return this.auth.authState;
  }
}

step 2. 將 AuthService 注入 Component

nember.component.ts

export class MemberComponent implements OnInit {

  constructor(
    public authService: AuthService,
  ) {
  }

step 3. 獲取用戶資料

使用注入的 authService.userData,取得用戶資料並綁定 template

nember.component.html

  <div class="menu-auth-data">
    <div *ngIf="authService.userData">
      <div id="memu-auth-photo">
        <img src='{{ this.authService.userData.photoURL }}' alt="auth.photo">
      </div>
      <div>
        {{ this.authService.userData.displayName }}
      </div>
      <div>
        {{ this.authService.userData.email }}
      </div>
    </div>
  </div>

參考資料

#AngularFire Quickstart #Angular #Firebase #Firestore #Google Sign-In #Firebase Authentication







你可能感興趣的文章

團隊的推進器 — 開放與學習

團隊的推進器 — 開放與學習

COSCUP 2022 信箱爆炸了

COSCUP 2022 信箱爆炸了

SCSS - map vs list / @for vs @each

SCSS - map vs list / @for vs @each






留言討論