我是聚合物和firebase的新手。我找不到关于聚合物的firebase-document元素的好文档。 我的问题是当新用户登录时,如何使用他的uid在firebase数据库中创建一个对象?
另外,请指出一些关于如何使用polymerfire firebase元素保存和查询数据的好例子。
答案 0 :(得分:2)
首先,您需要firebase-auth才能使身份验证魔术发生。例如,如果您要进行Google登录,则需要:
将这些属性分配给firebase-auth元素
<firebase-auth
id="auth"
user="{{user}}"
provider="google"
signed-in="{{signedIn}}">
</firebase-auth>
将点击/点击事件监听器分配给按钮
<button on-tap="signInWithGoogle">Sign In With Google</button>
按钮点击/点击
调用OAuth身份验证方法signInWithGoogle: function() {
this.$.auth.signInWithPopup();
}
现在,以下是将用户信息保存到firebase数据库的方法:
将这些属性分配给firebase-document元素(请注意path
属性此时无关紧要,因为它将被save()
方法覆盖)
<firebase-document
id="authDocument"
data="{{userData}}">
</firebase-document>
扩展signInWithGoogle()
方法
signInWithGoogle: function() {
// Chain then() method to the Promise
this.$.auth.signInWithPopup().then(function(response) {
// Update userData object with user information
// returned with signInWithPopup()
this.userData.displayName = response.user.displayName;
this.userData.email = response.user.email;
// Save userData object under /users/$uid. Note that at this
// point authDocument's path is now changed to /users/$uid
this.$.authDocument.save('/users', response.user.uid);
// And don't forget to bind this
}.bind(this));
}
希望有所帮助。这是单个元素的完整实现。请注意,firebase-app元素在父级中。
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/polymerfire/firebase-auth.html">
<link rel="import" href="../bower_components/polymerfire/firebase-document.html">
<dom-module id="my-account">
<template>
<style>
:host {
display: block;
}
</style>
<firebase-auth
id="auth"
user="{{user}}"
provider="google"
signed-in="{{signedIn}}">
</firebase-auth>
<firebase-document
id="authDocument"
data="{{userData}}">
</firebase-document>
<div hidden$="[[user]]">
<button on-tap="signInWithGoogle">Sign In With Google</button>
</div>
<div hidden$="[[!user]]">
<table>
<tr><th>photoURL</th> <td><img src="[[user.photoURL]]" alt=""></td></tr>
<tr><th>uid</th> <td>[[user.uid]]</td></tr>
<tr><th>displayName</th> <td>[[user.displayName]]</td></tr>
<tr><th>email</th> <td>[[user.email]]</td></tr>
<tr><th>emailVerified</th> <td>[[user.emailVerified]]</td></tr>
</table>
<button on-tap="signOut">Sign Out</button>
</div>
</template>
<script>
Polymer({
is: 'my-account',
signInWithGoogle: function() {
this.$.auth.signInWithPopup().then(function(response) {
this.userData.displayName = response.user.displayName;
this.userData.email = response.user.email;
this.$.authDocument.save('/users', response.user.uid);
}.bind(this));
},
signOut: function() {
this.$.auth.signOut();
}
});
</script>
</dom-module>