您好我在
中收到错误angular2-polyfills.js:143 Uncaught TypeError:无法设置属性' singlehotel' of null(...)
来自Firebase的警告
FIREBASE警告:用户回调引发了异常。 TypeError:无法设置属性' singlehotel'为null
当我尝试从Firebase获取数据时,我收到此错误,请任何人帮忙解决此问题。
提前致谢!
ngAfterContentInit() {
this.singlehotel = {};
firebase.database().ref('Rests/').once('value', function(snapshot) {
console.log('value from db' + JSON.stringify(snapshot.val()));
var getrest = snapshot.val();
console.log(JSON.stringify(getrest));
for (var key in getrest) {
if(restemail == getrest[key].email){
console.log(key + ':' + JSON.stringify(getrest[key]));
this.singlehotel = getrest[key]; //getting error here when using this
}
}
});
};
<script src="https://www.gstatic.com/firebasejs/3.5.1/firebase.js"></script>
<script>
// Initialize Firebase
// for security reasons i am hiding my keys
var config = {
apiKey: "***",
authDomain: "***",
databaseURL: "***",
storageBucket: "**",
messagingSenderId: "**"
};
firebase.initializeApp(config);
</script>
<body>
<my-app>Loading...</my-app>
</body>
<div class="container" style="background-color: #f2f2f2;">
<h1><b>Hotel Name :{{singlehotel.displayName}}</b></h1>
</div>
两者都属于同一个组件。当视图加载时,每次都会调用ngAfterContentInit()函数,这就是函数如何触发但我无法存储在范围内我的意思是这个。请帮助我
答案 0 :(得分:4)
this
, function() {... }
并不指向当前的类实例。请改用箭头功能
firebase.database().ref('Rests/').once('value', (snapshot) => {
另见https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions