简体   繁体   English

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

[英]Firebase: How to asynchronously bind User from firebase.auth().onAuthStateChanged to Angular template?

What I have tried:我试过的:

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

If I delay the function by 5000ms, it will bind to the template:如果我将 function 延迟 5000 毫秒,它将绑定到模板:

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

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

How do I dynamically determine that the onAuthStateChanged is ready?如何动态确定onAuthStateChanged已准备就绪? I am not using angularfire2/auth , and I would like to avoid it and instead use the standard Firebase JavaScript API.我没有使用angularfire2/auth ,我想避免使用它,而是使用标准 Firebase JavaScript API。

You could create your own Firebase Auth Angular Service and leverage RXJS observables to handle asynchronous initialization.您可以创建自己的 Firebase Auth Angular 服务并利用 RXJS 可观察对象来处理异步初始化。

firebase-auth.service.ts 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零件

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

Template模板

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 "firebase.auth().onAuthStateChanged 不工作" - firebase.auth().onAuthStateChanged Not Working 在 React 中放置 firebase.auth().onAuthStateChanged 的位置 - where to place firebase.auth().onAuthStateChanged in React firebase.auth().onAuthStateChanged 无限循环 - firebase.auth().onAuthStateChanged looping infinitely Firebase 和 React TypeError: firebase.auth(...).onAuthStateChanged 不是 function - Firebase and React TypeError: firebase.auth(...).onAuthStateChanged is not a function 类型错误:调用“firebase.auth().onAuthStateChanged((user)”时无法读取未定义的属性“auth” - TypeError: Cannot read property 'auth' of undefined when calling " firebase.auth().onAuthStateChanged((user)" firebase.auth()。currentUser和onAuthStateChanged始终为null,尽管已登录 - firebase.auth().currentUser and onAuthStateChanged always null inspite of being signed in 跨两个页面使用 firebase.auth().onAuthStateChanged 时的问题 - Issue when using firebase.auth().onAuthStateChanged accross two pages 刷新页面时,有时firebase.auth()。onAuthStateChanged返回null的用户 - Sometimes firebase.auth().onAuthStateChanged returns user of null when I refresh the page firebase.auth().onAuthStateChanged 登录后未执行? - firebase.auth().onAuthStateChanged not executed after sign-in? Javascript - firebase.auth().onAuthStateChanged 在登录/注销时未触发 - Javascript - firebase.auth().onAuthStateChanged not firing upon login/logout
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM