Firebase:如何将用户从firebase.auth()。onAuthStateChanged异步绑定到Angular模板?

时间:2019-10-07 22:38:53

标签: javascript angular firebase firebase-authentication

我尝试过的事情:

ngOnInit() {
    firebase.auth().onAuthStateChanged((user) => {
    console.log(user.uid); <-------------- Correctly showing in console
    this.uid = user.uid; <---------------- Not binding to html
    });
}

如果我将功能延迟5000ms,它将绑定到模板:

ngOnInit() {
  setTimeout(() => {
     this.getUid();
  }, 5000);
}

getUid(){
    firebase.auth().onAuthStateChanged((user) => {
    console.log(user.uid); <-------------- Correctly showing in console
    this.uid = user.uid; <---------------- Binding perfectly
    });
}

如何动态确定onAuthStateChanged已准备就绪?我没有使用angularfire2/auth,所以我想避免使用它,而是使用标准的Firebase JavaScript API。

1 个答案:

答案 0 :(得分:0)

您可以创建自己的Firebase Auth Angular服务,并利用RXJS可观察对象来处理异步初始化。

firebase-auth.service.ts

import { Injectable, Optional } from '@angular/core'
import * as firebase from 'firebase/app'
import 'firebase/auth'

import { BehaviorSubject } from 'rxjs'


@Injectable({
  providedIn: 'root'
})
export class FirebaseAuthService {
  public app: firebase.app.App;
  public auth: firebase.auth.Auth;
  public user$: BehaviorSubject<firebase.User> = new BehaviorSubject(null);

  // Note: FirebaseConfig is a class to enable injecting the Firebase app 
  // initialization params when providing the service in app.module.ts.
  constructor(@Optional() fb_config: FirebaseConfig) {
    // https://firebase.google.com/docs/reference/js/firebase.app.App
    this.app = firebase.initializeApp(fb_config);
    this.auth = firebase.auth(this.app);

    this.auth.onAuthStateChanged(
      (user: firebase.User) => {
        if (user) {
          this.user$.next(user);
          console.log('User signed in');
        } else {
          this.user$.next(null);
          console.log('User signed out');
        }
      },
      (error: firebase.auth.Error) => {
        // handle error
      }
    )
  }
  // ...
}

组件

@Component({
  moduleId: module.id,
  selector: 'my-component',
  templateUrl: 'my.component.html',
  styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
  constructor(private authService: FirebaseAuthService) {}
  // ...
}

模板

<ng-container *ngIf="( authService.user$ | async ) as user">
  <div>Hello {{user.displayName}}</div>
</ng-container>