如何获取 Observables 的值?

How to get the Observables value?

我在此处跟随 AngularFire 教程:https://angularfirebase.com/lessons/google-user-auth-with-firestore-custom-data/。我的问题是:如何在不同的组件中获取当前登录用户的 UID 和 displayName?我已经在导入和注入 AuthService(下面的服务),但如何访问 Firestore 中的这些字段?下面是相关代码。

@Injectable()
export class AuthService {
  user: Observable<User>;
  constructor(private afAuth: AngularFireAuth,
              private afs: AngularFirestore,
              private router: Router) {
      //// Get auth data, then get firestore user document || null
      this.user = this.afAuth.authState
        .switchMap(user => {
          if (user) {
            return this.afs.doc<User>(`users/${user.uid}`).valueChanges()
          } else {
            return Observable.of(null)
          }
        })
  }

  googleLogin() {
    const provider = new firebase.auth.GoogleAuthProvider()
    return this.oAuthLogin(provider);
  }

  private oAuthLogin(provider) {
    return this.afAuth.auth.signInWithPopup(provider)
      .then((credential) => {
        this.updateUserData(credential.user)
      })
  }

  private updateUserData(user) {
    // Sets user data to firestore on login
    const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.uid}`);
    const data: User = {
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL
    }
    return userRef.set(data)
  }

  signOut() {
    this.afAuth.auth.signOut().then(() => {
        this.router.navigate(['/']);
    });
  }
}

My question is: How would I fetch the currently signed in user's UID and displayName in a different component?

在不同的组件中,您可以注入此 authService 并可以使用 user 属性 这是一个可观察的。

如果你只想在组件中使用它:

user: User;
constructor(public auth: AuthService) { }

现在您可以订阅 auth.user 例如:

ngOnInit() {
  this.auth.user.subscribe((user) => {
    this.user = user;
    console.log(user)
    /* user.uid => user id */
    /* user.displayName => user displayName */
  })
}

或仅在 html:

 <div *ngIf="auth.user | async as user">
    <h3>Howdy, {{ user.displayName }}</h3>
    <img  [src]="user.photoURL">
    <p>UID: {{ user.uid }}</p>
    <p>Favorite Color: {{ user?.favoriteColor }} </p>
</div>