我无法将数据从Firebase传输到聚合物元素。
这是我的代码:
<dom-module id="bb-account-settings">
<template>
<style is="custom-style" include="shared-styles"></style>
<div class="settings-dialog">
<div class="frame">
<div class="horizontal layout">
<div>
<div class="user-image"></div>
</div>
<div class="horizontal layout">
<paper-input label="First Name" value="{{fNameSet}}"></paper-input>
      
<paper-input label="Last Name" value="{{lNameSet}}"></paper-input>
</div>
<paper-input label="Email" value="{{emailSet}}"></paper-input>
</div>
<paper-input label="Phone number" value="{{phoneSet}}" allowed-pattern="[0-9]"></paper-input>
</div>
</div>
</template>
<script>
Polymer({
is: 'bb-account-settings',
properties: {
fNameSet: {
type: String,
value: function() {
var userId = firebase.auth().currentUser.uid;
firebase.database().ref('/user/' + userId + '/UserInfo').once('value').then(function(snapshot) {
console.log(snapshot.val().fName)
return (snapshot.val().fName);
});
}
},
lNameSet: {
type: String,
value: 'test last name'
}
}
}
});
</script>
lNameSEst是“测试姓氏”,显然是将其放入其输入字段中。您很希望fNameSet可以用于相同的东西,但是不可以。当我打印它(console.log)时,它显示“ test first name”(测试名字),但它不会显示在输入字段中!
我很困惑。
最佳答案
正如其中一位评论者所注意到的那样,问题在于在回调中返回值。传递给firebase的“一次”函数的函数被异步调用并且在不同的范围内,因此从根本上讲,它失去了与声明它的位置的关系,并且所返回的值不会到达期望的位置。
一种获取您想要的东西的蛮力方法是执行以下操作:
ready: function() {
var userId = firebase.auth().currentUser.uid;
firebase.database().ref('/user/' + userId + '/UserInfo').once('value').then(function(snapshot) {
console.log(snapshot.val().fName)
this.fNameSet = snapshot.val().fName;
}.bind(this));
}
有更多优雅的方法,但这超出了此问题的范围,并且需要一些重新构造和对应用程序结构的更深入了解。
关于javascript - 从Firebase到Polymer元素检索数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38368392/