[AngularFire2] Building an Authentication Observable Data Service
2024-10-01 22:04:37
After successfully login, we want something help to check whether user has already login or not. And we will use Observable to do that.
Create AuthInfo.ts:
export class AuthInfo {
constructor(private uid$: string){ } isLoggedIn() {
return !!this.uid$;
}
}
The class is very simple, accpets an uid which return from FirebaseAuth, and a method to check whether id is set already.
TO user Observable to handle the data:
AuthService.ts:
static UNKNOW_USER = new AuthInfo(null); // Create a default unknow user
public authInfo$: BehaviorSubject<AuthInfo> = new BehaviorSubject<AuthInfo>(AuthService.UNKNOW_USER); // We user BehaviorSubject to to conver to Observable, Behavior Subject already needs a default value, so we can repersent logout status by using default value
login(email, password) { return this.fromFirebaseAuthPromise(this.auth$.login({
email, password
},{
method: AuthMethods.Password,
provider: AuthProviders.Password
}));
} fromFirebaseAuthPromise(promise) {
const subject = new Subject<any>(); promise.then((res) => {
const uid = this.auth$.getAuth().uid;
const authInfo = new AuthInfo(uid);
this.authInfo$.next(authInfo);
subject.next(res);
subject.complete();
}, err => {
this.authInfo$.error(err);
subject.error(err);
subject.complete();
}); return subject.asObservable();
}
Everytime,we successfully login, will emit a uid.
So to show / hide show content based on 'authInfo$', we can do:
<md-list-item>
<a
*ngIf="authInfo$.isLoggedIn()"
[routerLink]="['/heros', {outlets: {'wiki': null}}]"
routerLinkActive="active"
[routerLinkActiveOptions]="{exact: true}"
>Heros</a>
</md-list-item>
authInfo$;
constructor(private auth: AuthService){
this.auth.authInfo$.subscribe(
res => {
this.authInfo$ = res;
}
)
}
最新文章
- elasticsearch中常用的API
- vim符号列表窗口
- [问题2014A13] 解答
- DataSet key points
- 转 java int与Integer的区别
- Oracle SQL语句追踪
- 使用apt-get方式为Kubuntu安装PHP+MYSQL+Apache
- JAVA多态需要注意的一些问题
- Spring4.0学习笔记(1) —— 基础知识
- margin 属性的相关问题
- VS+VA 开发NDK
- java封装的方法
- linux----------linux下安装rar和unrar命令
- 算法之Python实现 - 001 : 换钱的最少货币数
- NHibernate删除数据时遇到deleted object would be re-saved by cascade级联问题
- c# Cache 使用实例
- linux命令总结iostat命令
- SpringBootTest单元测试实战、SpringBoot测试进阶高级篇之MockMvc讲解
- [django]django corepython核心编程
- 获取当前人IP地址
热门文章
- Trafodion:Transactional SQL on HBase
- 【UWP通用应用开发】控件、应用栏
- 关于XAMPP安装后APACH无法启动的问题
- jquery的图片轮播 模板类型
- USACO 2009 Dec cow toll paths 过路费-floyd
- Unity实现发送QQ邮件功能
- 在一台机子上,安装,运行两mysql数据库实例
- 通过Ajax进行POST提交JSON类型的数据到SpringMVC Controller的方法
- Android RecyclerView And CardView
- Excel查询序列所相应的值-vLoopup函数,求比例分子改变但分母不变