当用户在会话中首次登录仪表板时,我遇到了这个问题。
登录后,我将用户重定向到私有视图,使用此服务从 Firestore 检索其数据:
getUser():Observable<DocumentSnapshot<DocumentData>> {
const uid = this.user$?.uid;
const userRef = doc(this.firestore,'users/' + uid)
return from(
getDoc(userRef)
);
然后,在仪表板布局组件(模块其余部分的父组件)中,我像这样实现服务:
export class DashboardLayoutComponent implements OnInit{
constructor(private auth:AuthService) {}
public user:CustomUser;
public loading:boolean = true;
ngOnInit(){
this.auth.getUser().subscribe(res =>{
this.luxorUser = res.data() as CustomUser;
this.loading = false;
});
}
}
当用户到达仪表板布局时,变量 user 未定义。但是,当我重新加载页面时,数据已正确分配给界面。此外,一些子组件使用 @Output 装饰器读取 CustomUser 对象,因此它们永远不会出现,因为它们接收的是未定义的而不是对象。
一旦我强制重新加载,一切都会按预期进行。
这是我迄今为止尝试过的
我会尝试创建一个带有主题的服务
...
isUser$ = new Subject<void>();
...
然后
ngOnInit(){
this.auth.getUser().subscribe(res =>{
this.luxorUser = res.data() as CustomUser;
if ( this.luxorUser ) {
this.subjectService.isUser$.next();
this.loading = false;
}
});
然后在你的组件中
this.subjectService.isUser$.pipe(
tap( _ => this.userService.getUser()
).subscribe()