我尝试调用提供程序中一部分的函数,但是我注意到
调用位于firebase.auth().onAuthStateChanged
函数内部,所有提供程序都未定义。
@ Ionic3.9.2 @ cordova-8.1.2(cordova-lib@8.1.1)
那是我的代码:
constructor(public global:global,public navCtrl: NavController, public navParams: NavParams, public app: App, public dataProvider: DataProvider,
public loadingProvider: LoadingProvider, public alertProvider: AlertProvider, public alertCtrl: AlertController, public firebaseProvider: FirebaseProvider, public modalCtrl: ModalController) { }
ionViewDidLoad() {
console.log(this.dataProvider);
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
// User is signed in.
console.log(user);
this.currentUser=user;
this.tab = "friends";
this.title = "Friends";
this.searchFriend = '';
console.log(this.dataProvider); /* -> undefined*/
if (this.dataProvider.getRequests(this.currentUser != null)) { /* the console return to me an error :TypeError: Cannot read property 'getRequests' of undefined */
console.log(this.dataProvider.getRequests(this.currentUser));
// console.log(this.dataProvider.getRequests(firebase.auth().currentUser.uid));
console.log("if ");
// console.log(this.currentUser.uid);
console.log(this.currentUser);
this.dataProvider.getRequests(this.currentUser.uid).snapshotChanges().subscribe((requestsRes) => {
let requests = requestsRes.payload.val();
console.log(requests);
if (requests != null) {
if (requests.friendRequests != null && requests.friendRequests != undefined)
this.friendRequestCount = requests.friendRequests.length;
else this.friendRequestCount = 0
}
else this.friendRequestCount = 0;
console.log(this.friendRequestCount);
});
this.getFriends();
}
} else {
// No user is signed in.
console.log('no User');
}
});
我确信我会错过一些东西,并感谢您的帮助!
答案 0 :(得分:0)
好,我找到了解决方法
说明: 全部与“ this”关键字有关
回调函数中的this.dataProvider与回调函数外部的this.dataProvider不同。
要在回调函数的内部和外部引用相同的this.dataProvider,您只需创建一个函数并将dataProvider作为参数传递。
constructor(public global:global,public navCtrl: NavController, public navParams: NavParams, public app: App, public dataProvider: DataProvider,
public loadingProvider: LoadingProvider, public alertProvider: AlertProvider, public alertCtrl: AlertController, public firebaseProvider: FirebaseProvider, public modalCtrl: ModalController) {
this.ionViewDidLoad(this.dataProvider); // <--- with this (mandatory)
}
ionViewDidLoad(dataProvider: DataProvider) {
console.log(dataProvider); // <-- defined with or without this
firebase.auth().onAuthStateChanged(function (user) {
.........
console.log(dataProvider); /* without this -> NOT undefined anymore :) */
})