zoukankan      html  css  js  c++  java
  • [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;
            }
          )
      }
  • 相关阅读:
    iOS总结_UI层自我复习总结
    runtime梳理。
    页面传值。顺传,逆传。
    用1 + 2 = 3诠释面向对象思想
    循环逻辑。让我逻辑滞空的小题目
    const,static,extern 简介
    swift webView的高度自适应内容
    Swift之UITabBarController 导航控制器颜色的改变
    swift 启动图片的设置
    swift 中使用OC第三方库(以AFNetworking为例)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6087731.html
Copyright © 2011-2022 走看看