【发布时间】:2019-06-26 15:02:47
【问题描述】:
我最近在构造函数中添加了 onAuthStateChanged 函数,如果用户不为空,那么我调用一个函数来获取帖子(事件)。但是,直到我单击页面中的某个位置然后数据显示后,该函数的数据才会加载。没有显示错误。
我尝试清除 onAuthStateChanged 并且数据加载正常,但我需要在此页面中添加 firebase 的安全性。
这是我的 feed.ts 和函数 getEvents()
public async getEvents() {
this.events = [];
const loading = await this.loadingCtrl.create({
message: 'Loading events...'
});
loading.present();
const query = firebase.firestore().collection('events').orderBy('created', 'desc').limit(this.pageSize);
query.onSnapshot((snapshot) => {
const changedDocs = snapshot.docChanges();
changedDocs.forEach((change) => {
if (change.type == 'modified') {
for (let i = 0; i < this.events.length; i++) {
if (this.events[i].id === change.doc.id) {
this.events[i] = change.doc;
}
}
}
})
})
query.get().then((events) => {
events.forEach((event) => {
this.events.push(event);
});
loading.dismiss();
if (events.size == 0) {
this.cursor = 0;
} else {
this.cursor = this.events[this.events.length - 1]; // the last index of the collection
}
console.log(this.events);
}).catch((err) => {
console.log(err);
});
}
这是我调用函数 getEvents() 的构造。当我打开应用程序时会显示加载消息,但除非我单击应用程序上的任何位置,否则不会显示数据。
constructor(public navCtrl: NavController, private loadingCtrl: LoadingController, private toastCtrl: ToastController, private http: HttpClient, public actionSheetCtrl: ActionSheetController, public alertCtrl: AlertController, public modalCtrl: ModalController, public popoverCtrl: PopoverController, private location: Location, ) {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.getEvents();
} else {
this.location.replaceState('/');
this.navCtrl.navigateForward('login');
}
});
// this.getEvents();
}
如果我在条件 if(user) { ...
之外调用它,该函数可以正常工作【问题讨论】:
标签: firebase ionic-framework firebase-authentication ionic4