从firebase数据库中获取用户密钥

时间:2017-07-15 12:23:36

标签: angular firebase firebase-realtime-database angularfire2

我有用户数据存储在数据库中

users: {
  -Kp56mwwpFiCwIXLszqu: {
     email: "testemail@gmail.com",
     name: "test name",
     username: "testname"
  },
  -Kp58X2WGUVNazSSbRqF: {
     email: "anotheruser@gmail.com",
     name: "another user",
     username: "anotheruser"
  }
}

有没有办法获取用户的密钥,例如-Kp56mwwpFiCwIXLszqu-Kp58X2WGUVNazSSbRqF

我想向现有用户添加更多集合。例如。我以testname身份登录,我想从数据库中获取testname密钥,以便我可以在那里推送更多的集合。

感谢任何帮助。谢谢

1 个答案:

答案 0 :(得分:1)

这些键看起来像自动生成的键。您可能希望通过将其数据保存在uid下来更改在数据库中保存用户配置文件的方式。

例如:

// Definition of the user profile class.
export class UserProfile {
    email: string;
    name: string;
    username: string;
}

----------------------------------------------------

// Inside of some service.
constructor(
    private angularFireAuth: AngularFireAuth,
    private angularFireDatabase: AngularFireDatabase
) { }

saveUserProfile(profile: UserProfile): firebase.Promise<void> {
    let currentUserUid = this.angularFireAuth.auth.currentUser.uid;
    return angularFireDatabase.object(`users/${currentUserUid}`).update(profile);
}

这应该将用户个人资料数据保存在他的uid下。请注意,我使用update方法而不是push,因为push生成一个新的唯一键,与updateset不同。那么您的数据将具有以下结构:

users: {
    {user_uid_will_be_here}: {
        email: 'someone@example.com',
        name: 'Test User',
        username: 'myusername'
    }
}

然后,您可以在以后通过当前登录的用户uid简单地访问该数据。

getCurrentUserProfile(): UserProfile {
    let currentUserUid = this.angularFireAuth.auth.currentUser.uid;
    return this.angularFireDatabase.object(`users/${currentUserUid}`);
}
相关问题