首页 > 解决方案 > Angular - 从 Firestore 获取单个文档时遇到问题

问题描述

我正在尝试创建一个用户列表,这是 Firestore 中的一个集合,然后用户将能够单击用户并被重定向到具有更多数据的用户个人资料页面。我能够显示数据;但是,对于集合中的每个其他文档,我都收到一个控制台错误,说找不到属性。

用户配置文件.ts:

 ngOnInit() {
//get user id from route
this.uid = this.route.snapshot.params['uid'];

//get user document reference from firestore using auth service
this.authService.getUserDocById(this.uid).get().then(doc =>{
    this.user = doc.data();
  }
);

if(this.uid == this.authService.getFirebaseUser().uid){
  this.isOwnProfile = true;
}
else{
  this.isOwnProfile = false;
 }
}

auth.service.ts:

getUserDocById(uid: string)
  {
    var path = ('users/' + uid);
    return this.afs.doc(path).ref; 
  }

用户配置文件.component.html:

  <div class="imagewrapper">
  <div [ngClass]="{ 'isOwnImage' : isOwnProfile }" [ngStyle]="{ 'background-image': 'url(' + user.profileImageUrl + ')' }" class="profileImage"></div>

除了我当前正在查看的用户之外,无论集合中有多少用户,我都会收到此控制台错误:

TypeError: Cannot read property 'profileImageUrl' of undefined
    at Object.eval [as updateDirectives] (UserProfileComponent.html:2)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:10853)
    at checkAndUpdateView (core.js:10250)
    at callViewAction (core.js:10491)
    at execComponentViewsAction (core.js:10433)
    at checkAndUpdateView (core.js:10256)
    at callViewAction (core.js:10491)
    at execEmbeddedViewsAction (core.js:10454)
    at checkAndUpdateView (core.js:10251)
    at callViewAction (core.js:10491)

标签: javascriptangulartypescriptfirebasegoogle-cloud-firestore

解决方案


推荐阅读