Firebase 提供了简单的Authentication,让开发者不需要自己Server端开发身分验证的机制. Firebase 提供了Email/Password, Google, Facebook, Twitter等等的登入机制, 这篇主要是介绍如何在IONIC 使用Firebase Email/Password功能.
首先导入模组import { AngularFireAuth } from '@angular/fire/auth';
.我通常会有AuthService
, 分别有 register
,login
, signout
方法.
register(email:string, password:string){ return this.afAuth.auth.createUserWithEmailAndPassword(email,password); }
方法createUserWithEmailAndPassword
会回传一个Promise, 成功后就切换到 Login页面.
this.authService.register(this.user.email, this.user.password).then((res: any) => { this.router.navigateByUrl('path'); }) .catch((error: any) => console.error(error));
在login方法里使用方法如下,一样会回传一个Promise.
this.afAuth.auth.signInWithEmailAndPassword(email, password)
在成功会传Response, 我用Subject去通知有订阅这个Subject的Function,去做login后的页面呈现.
//宣告一个Subjectpublic authSubject = new Subject<boolean>();....//更新Subject的值,并做通知 this.authSubject.next(true); ....//任何订阅这个subject都可以取得现在Authentication的状态. this.authService.authSubject.subscribe((isAuth)=>{ this.isAuth = isAuth; });
因为登入后user会暂存在Memory,下次使用App始就不需要在登入, 如何让App知道暂存的user, 我们可以使用如下的方法,同样的使用authSubject去通知App.
this.afAuth.auth.onAuthStateChanged((user: firebase.User)=>{ if(user){ this.authSubject.next(true); console.log('user found'); }else{ this.authSubject.next(false); console.log('user not found'); this.router.navigate(['tabs/login']); } });
signout 非常简单
this.afAuth.auth.signOut().then(function() { console.log('Logout Succcess!'); this.router.navigateByUrl('tabs/login'); }).catch(function(error) { console.log(error); });
以上是我用Firebase 身分验证机制,如果有任何错误或是补充,欢迎回覆!