首页 > 解决方案 > Angular 不会在异步任务中显示任何类型的 Observable userdata

问题描述

我的 home.component.html 不会显示我的 userData:

<h1 class="display-4">Hello, {{ (userData | async)?.username }}</h1>

这是来自 home.component.ts 的调用:

  ngOnInit(): void {
    this.userData = this.userService.getUser();
  }

这是服务:

export class UserService {

  private userDoc: AngularFirestoreDocument<any>;
  user: Observable<Userdata>;

  constructor(private authService: AuthService, private afs: AngularFirestore ) { 

    this.userDoc = this.afs.doc<any>('users/'+ this.authService.getUserId());
    this.user = this.userDoc.valueChanges();

  }

  getUser(){
   return this.user
  }

这是身份验证服务:

  constructor(public  afAuth:  AngularFireAuth, 
              public  router:  Router,
              private firestore: AngularFirestore) {  
                console.log("Constructor for Auth Service")               
                this.afAuth.authState.subscribe(userData => {
                  if (userData) {
                    this.router.navigate([''])
                    this.user = userData;
                      if(this.user.emailVerified == false){
                        this.user.sendEmailVerification()
                      }
                    }
                })
              }

  getUserId(){
    if(this.user){
      return this.user.uid;
    } else {
      return null;
    }

  }

但 html 中没有显示任何内容: 主页 组件视图

这是我在 home 组件中记录用户数据时得到的: 服务调用后登录 home 组件

希望有人可以帮忙

标签: angularasynchronousgoogle-cloud-firestorepipeobservable

解决方案


您可以尝试在控制台中打印数据

this.user = this.afs
  .collection<any>('users/'+ this.authService.getUserId())
  .valueChanges()
  .pipe(
    tap(ref => console.log(ref)
  );

推荐阅读