I'm trying to execute function when page opens. I have typescript code:
export class MyReservationsPage implements OnInit {
user: any;
userId: string;
storedData: any = [];
constructor(private auth: AuthService, private afs: AngularFirestore) {}
ngOnInit() {
this.fetchBookings();
}
fetchBookings() {
this.afs
.collection('user')
.doc(this.userId)
.collection('BookingHistory')
.get()
.subscribe((querySnapshot) => {
this.storedData = querySnapshot.docs.map((e) => {
return {
bookingDate: e.data()['Merge'],
};
});
});
}
}
and HTML:
<ion-content>
<ion-grid>
<row *ngFor="let data of storedData">
<ion-col *ngFor="let value of data.bookingDate">
<ion-row>{{value.Date}}</ion-row>
<ion-row>{{value.Time}}</ion-row>
<ion-row>{{value.BookedAt.toDate() | date:'medium'}}</ion-row>
</ion-col>
</row>
</ion-grid>
</ion-content>
I don't really know how ngOnInit
works but How I can execute function automatically without clicking on button?
CodePudding user response:
The ngOnInit
doesn't fire every time:
A callback method that is invoked immediately after the default change detector has checked the directive's data-bound properties for the first time, and before any of the view or content children have been checked. It is invoked only once when the directive is instantiated.
Source: Angular Docs
If you want to call the function every time the view loads, you'd be better off using the Ionic lifecycle events detailed here.
So in your case, you could use something like:
export class MyReservationsPage {
user: any;
userId: string;
storedData: any = [];
constructor(
private auth: AuthService,
private afs: AngularFirestore
) {}
ionViewDidEnter() {
this.fetchbookings();
}
fetchBookings() {
this.afs
.collection('user')
.doc(this.userId)
.collection('BookingHistory')
.get()
.subscribe((querySnapshot) => {
this.storedData = querySnapshot.docs.map((e) => {
return {
bookingDate: e.data()['Merge'],
};
});
});
}
}
That will call your fetchBookings()
method after the view has loaded.