# 中繼器2 ###### tags: `CTBC-Lab4` ## firebase ![](https://hackmd.io/_uploads/r18tSu043.png) ## 程式碼 auth.services.ts ```typescript= import { Injectable } from '@angular/core'; import { AngularFireAuth } from '@angular/fire/compat/auth'; import { Router } from '@angular/router'; import { LocalStorageService } from 'ngx-webstorage'; import firebase from '@firebase/app-compat'; //import { getAuth, setPersistence, inMemoryPersistence, GoogleAuthProvider, signInWithPopup, } from "firebase/auth"; import 'firebase/compat/auth'; //import { GoogleAuthProvider } from 'firebase/auth'; import 'firebase/compat/firestore'; @Injectable({ providedIn: 'root' }) export class AuthService { user: any //此變數將在login.component.ts檔使用 constructor( public auth: AngularFireAuth, public router: Router, private storage: LocalStorageService, ) { // 訂閱firebase服務提供的「登入狀態」資料流 // authState 登入登出的狀態 this.auth.authState.subscribe((user)=>{ if (user) { this.user = user; this.storage.store('user',this.user); // 寫入local storage } }); } // auth為一外部服務,需設定為public // 1. 登入(email燈入) // .then() 為正常情況 (登入成功) // 1. 寫到localstore // 2. 轉到首頁 // () 內可以填寫其他功能 // () => {} login(mail:string,passwd:string){ this.auth.signInWithEmailAndPassword(mail,passwd).then( async (uc) => { console.log(uc.user); this.router.navigate(['/student']); }).catch( (error) => { console.log(error) }); } // 檢查是否已登入 isLoggedIn(): boolean { const user = this.storage.retrieve('user'); // ts檔 if else 縮寫 return (user !== null) ? true : false; } // 2. 登出 logout() { // Promise this.auth.signOut().then( () => { this.storage.clear('user'); console.log('登出成功') this.router.navigate(['/login']); // 跳回至login頁面 }).catch( error => { console.log('登出失敗') // 可不寫,因為登出較少失敗 } ) } // 使用Google登入 loginWithGoogle() { //const provider = new GoogleAuthProvider(); //firebase.auth() return this.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider()) .then(async(uc) => { console.log(uc); await this.storage.store('user',uc.user) this.router.navigate(['/dashboard']); }).catch(); } } ```