Using Provider Inside firebase.auth().onAuthStateChanged ret



>我尝试调用一个函数,它是提供程序的一部分,但我注意到当 调用在函数firebase.auth().onAuthStateChanged所有提供程序都未定义。

@Ionic3.9.2 @cordova-8.1.2 (科尔多瓦-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');
}
});

我相信我错过了一些东西,并感谢一些帮助谢谢!

好的,我找到了解决方案

解释: 一切都与"这个"关键字有关

回调中的 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 :) */
})

相关内容

  • 没有找到相关文章