我尝试过的:
ngOnInit() {
firebase.auth().onAuthStateChanged((user) => {
console.log(user.uid); <-------------- Correctly showing in console
this.uid = user.uid; <---------------- Not binding to html
});
}
如果我将函数延迟 5000 毫秒,它将绑定(bind)到模板:
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。
最佳答案
您可以创建自己的 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>
关于javascript - Firebase:如何将用户从 firebase.auth().onAuthStateChanged 异步绑定(bind)到 Angular 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58277997/