我的目标是将数据从一个页面传递到另一个页面。但是这个错误让我烦恼。我在构造函数
声明了navCtrl我的request.ts构造函数
constructor(public navCtrl: NavController, public navParams: NavParams, angFire: AngularFireDatabase) {
this.request = angFire.list('/request');
this.userreq = angFire.list(`${this.userkey}`);
this.reqdetails = angFire.list('reqdetails');
}
我的request.html
的html页面<button class="nearby" ion-button large (click)="openMapPage()">Nearby</button>
我对request.ts的OpenPage方法
openMapPage()
{
var ref = firebase.database().ref("request");
ref.once("value")
.then(function(snapshot) {
var a = snapshot.exists(); // true
var c = snapshot.hasChild("reqdetails"); // true
var d = snapshot.child('reqdetails').exists();
var requestsKey = snapshot.key;
var requestsValue = snapshot.val();
snapshot.forEach(function(childSnapshot) {
var requestKey = childSnapshot.key;
var requestValue = childSnapshot.val();
var reqdetails = requestValue.reqdetails;
if(reqdetails)
{
this.data = requestKey;
console.log(this.data);
//this.arr.push(requestKey);
//console.log(this.arr);
}
});
this.navCtrl.push(MapPage, {'param1':this.data});
});
}
因此,在用户点击来自request.html的OpenMapPage()之后,它将转到reqeuest.ts中找到的openMapPage方法,并将数据呈现到map.html页面
我的map.html页面:
<ion-list>
<ion-card *ngFor="let user of request | async" class="job">
<ion-avatar class="avatar" item-start>
<img src="../assets/icon/user_male-512.png">
</ion-avatar>
<h2 class="name">{{user.regdetails.username}}</h2>
<p text-wrap class="address"><ion-icon name="compass"></ion-icon> {{user.regdetails.address}}</p>
<p id="key">{{user.$key}}</p>
</button>
</ion-card>
</ion-list>
答案 0 :(得分:1)
您在snapshot.forEach
中使用常规函数作为回调。
使用箭头功能,以便this
引用类对象或使用临时变量在通话前保存this
。
snapshot.forEach((childSnapshot) => {
var requestKey = childSnapshot.key;
var requestValue = childSnapshot.val();
var reqdetails = requestValue.reqdetails;
if(reqdetails)
{
this.data = requestKey;
console.log(this.data);
//this.arr.push(requestKey);
//console.log(this.arr);
}
});
注意:也可以在外部回调中使用箭头功能
答案 1 :(得分:1)
您应该使用 Arrow functions 。通过使用箭头函数,this
属性不会被覆盖,仍会引用组件实例(否则,this关键字指向内部函数,并且组件的方法和变量未在其中定义):
openMapPage() {
var ref = firebase.database().ref("request");
ref.once("value").then((snapshot) => { // <------ Here!
var a = snapshot.exists(); // true
var c = snapshot.hasChild("reqdetails"); // true
var d = snapshot.child('reqdetails').exists();
var requestsKey = snapshot.key;
var requestsValue = snapshot.val();
snapshot.forEach((childSnapshot) => { // <------ And here!
var requestKey = childSnapshot.key;
var requestValue = childSnapshot.val();
var reqdetails = requestValue.reqdetails;
if (reqdetails) {
this.data = requestKey;
console.log(this.data);
//this.arr.push(requestKey);
//console.log(this.arr);
}
});
this.navCtrl.push(MapPage, { 'param1': this.data });
});
}