[AngularFire2] Building an Authentication Observable Data Service

本文介绍了一种利用Angular和Firebase实现用户登录状态检查的方法。通过创建`AuthInfo`类来管理用户的登录信息,并使用`BehaviorSubject`来处理登录状态的变化,实现了根据登录状态显示或隐藏页面内容的功能。

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

 

转载于:https://www.cnblogs.com/Answer1215/p/6087731.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值