[AngularFire2] Building an Authentication Observable Data Service

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;
        }
      )
  }

 

posted @   Zhentiw  阅读(343)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2015-11-22 [ES6] Converting an array-like object into an Array with Array.from()
2014-11-22 [ES6] 11. String Templates
2014-11-22 [AngularJS] $interval
2014-11-22 [ES6] 10. Array Comprehensions
点击右上角即可分享
微信分享提示