简体   繁体   English

使用 AngularFire2 和 Firebase 获取连接数据时出错

[英]Error getting joined data with AngularFire2 and Firebase

My database consists of two 'tables' with messages and users, with the messages having an senderID that matches an userID.我的数据库由两个带有消息和用户的“表”组成,消息的发送者 ID 与用户 ID 相匹配。 I am using the following code to join these two together when fetching the data获取数据时,我使用以下代码将这两者连接在一起

this.messages = this.af.database.list(`/messages/1`)
    .map(messages => {
      messages.map(message => {
        this.af.database.object('users/' + message.sender)
          .subscribe(user => {
            message.userdata = user;
            console.log(message);
          });
        return message;
      });
      return messages;
    });

console.log on the message shows the structure I am after, however, when i use {{item.userdata.provider.displayName}} it gives me the following TypeError: Cannot read property 'provider' of undefined消息上的 console.log 显示了我所追求的结构,但是,当我使用{{item.userdata.provider.displayName}}它给了我以下TypeError: Cannot read property 'provider' of undefined

Thankful for advice.感谢您的建议。

You can't depend on message.userdata being populated.您不能依赖于 message.userdata 被填充。 You're making an asynchronous call to fetch the data from the server, but not waiting for all of the users to be downloaded before rendering your UI.您正在进行异步调用以从服务器获取数据,但在呈现您的 UI 之前并不等待所有用户都被下载。

Additionally, you should consider the case that a user may not exist.此外,您应该考虑用户可能不存在的情况。 So you won't be able to use {{item.userdata.provider.displayName}} without at least an trying item.userdata?因此,如果至少没有尝试过item.userdata?您将无法使用{{item.userdata.provider.displayName}} item.userdata? first.第一的。

I'd guess there's a much better way to go about this, such as creating an item.getUserName() method that can handle these implementation details a bit more transparently and elegantly.我想有更好的方法来解决这个问题,例如创建一个item.getUserName()方法,可以更透明和优雅地处理这些实现细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM