[英]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 可观察对象来处理异步初始化。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.