无法使用 DocumentSnapshot 中的 属性 data()

Cannot use the property data() from DocumentSnapshot

我无法在 DocumentSnapshot 上使用 属性 data()。它在控制台中给我一个错误。这是确切的错误:

auth.service.ts(72,20): error TS2339: Property 'data' does not exist on type 'Observable'.

我尝试以多种不同的方式获取数据。所有这些技术都是错误的。

服务:

constructor(
  private afAuth: AngularFireAuth,
  private afs: AngularFirestore,
  private router: Router,
  public db: AngularFirestore
) {
    this.user = afAuth.authState;

    this.user.subscribe((user) => {
      if (user) {
        this.userDetails = user;
        console.log(this.userDetails);
      } else {
        this.userDetails = null;
      }
    })
}

getUserName() {
  (this.isLoggedIn()){
    const userD = this.db.collection('users').doc(this.userDetails.uid);
    const doc = userD.get();
    return doc.data().firstName;
  } else {
    console.log('user not logged in');
    return "nothing";
  }
}

根据此文档,您不能使用 userD.get().data()。尝试 userD.get()userD.data()

const userD = this.db.collection('users').doc(this.userDetails.uid);

var getOptions = {
  source: 'cache'
};

userD.get(getOptions).then(function (doc) {
    // check if firstname exist in doc
     console.log(doc)
 }).catch(function (error) {
 });

我关注https://cloud.google.com/firestore/docs/query-data/get-data

userD.get() return你是 DocumentSnapshot 的可观察者,所以你不能调用 data()。所以你需要订阅。在这种情况下,您似乎想要 return 数据到一个组件(?)所以我建议您 return 一个可观察的:

import { take, map } from 'rxjs/operators';

// ...

getUserName() {
  if(this.isLoggedIn()){
    const userD = this.db.collection('users').doc(this.userDetails.uid);
    const doc = userD.get();
    return doc.pipe(
      // add take if you only want data one time, which closes subscription
      take(1),
      map(d => d.data().firstName)
    )
  } else {
    console.log('user not logged in');
    // need to return an observable
    return of("nothing");
  }
}

然后在您的组件中订阅 getUserName(),方法是手动调用 subscribe 或使用模板中的 async 管道。