为什么 Angular Firestore return 数据也会产生错误?

Why does Angular Firestore return data and also generate errors?

我有一个从 firestore 文档中提取用户数据的用户配置文件。文档 returns 数据符合预期,但是,在控制台中我收到 8 个相同的错误,表明数据未定义。

我获取用户数据的代码如下:

TS:

export class UserProfileComponent implements OnInit {
  activeUserID: string;
  userRef: AngularFirestoreDocument<User>;
  userData;

  constructor(public afAuth: AngularFireAuth, private db: AngularFirestore) {
    this.getActiveUser();
  }

  ngOnInit() {

  }

  async getActiveUser(){
    const user = await this.afAuth.currentUser;
    this.activeUserID = user.uid;
    this.getUserId();
    this.getUserData();
  }

  getUserId(){
    this.userRef = this.db.collection('users').doc(this.activeUserID);
  }

  getUserData(){
    this.db.collection('users').doc(this.activeUserID).ref.get().then((doc) => {
      this.userData = doc.data();
    });
  }
}

HTML:

<div class="col-md-5">
  <h2>{{userData.displayName}}</h2>
  <h6>{{userData.username}}</h6>
  <p>This is a description about the user.</p>
</div>

此外,如果我 console.log 用户数据,它 returns 未定义,具体取决于它的输出位置。

控制台截图:

core.js:6228 ERROR TypeError: Cannot read property 'displayName' of undefined
    at UserProfileComponent_Template (user-profile.component.html:10)
    at executeTemplate (core.js:12156)
    at refreshView (core.js:11995)
    at refreshComponent (core.js:13445)
    at refreshChildComponents (core.js:11716)
    at refreshView (core.js:12051)
    at refreshEmbeddedViews (core.js:13391)
    at refreshView (core.js:12022)
    at refreshComponent (core.js:13445)
    at refreshChildComponents (core.js:11716)

doc.data() 的 TypeScript 签名表明它可以 return 未定义。当您的查询位置没有文档时,就会发生这种情况。由于 Firestore 不保证查询时文档的存在,您应该在使用前检查文档数据是否存在。

该错误消息是 TypeScript 专门告诉您您正在尝试引用对象上的 属性 实际上可能是未定义的,这会导致崩溃。你应该在使用它之前检查它是否有一个对象值,如果它不存在你还要决定你想做什么。

this.db.collection('users').doc(this.activeUserID).ref.get().then((doc) => {
  const data = doc.data();
  if (data) {
    // in this block, TypeScript guarantees you that data will have an object value
    this.userData = data;
  }
  else {
    // what do you want to do if it doesn't exist?
  }
});