esdoodle
esdoodle

Reputation: 347

Ionic Tabs Don't Enter the Page's Constructor More Than Once

I'm trying to make a notification page which is opening from tabs. After opening the page, it needs to refresh itself so the new notifications will be visible as well as these notifications will be checked as read and the badge on the tabs will be 0.

The first time you open the notification page, it enters the constructor but it doesn't enter again.

It was working well before but then it stops working, I don't know why.

Notification Page;

constructor(public events: Events, public navCtrl: NavController, public 
  navParams: NavParams, private notificationservice: NotificationService, 
  private loadingCtrl: LoadingController) {

this.notificationservice.getNotifications(AuthService.currentUser.UserId).then(
data => {
  this.notifications = data;

  this.notificationservice.unreadNotificationCount().then(data => {
    if(data != 0)
    {
      this.notificationservice.readNotification().then(data => {
        this.updateBadge();
        this.navCtrl.setRoot(this.navCtrl.getActive().component);
      });
    }
  });
});
}

public updateBadge()
{
  this.notificationservice.unreadNotificationCount().then(data => {
    console.log(data);
    this.events.publish('cart:updated', data);
  });
}

Tabs Page;

constructor(public navCtrl: NavController, public navParams: NavParams, 
private notificationservice: NotificationService, public events: Events) {

  this.updateBadge();

  this.events.subscribe('cart:updated', (count) => {      
    this.badge = count;
  });
}

public updateBadge()
{
  this.notificationservice.unreadNotificationCount().then(data => {
    console.log(data);
    this.events.publish('cart:updated', data);
  });
}

Tabs view;

Tabs with badge

Upvotes: 3

Views: 1788

Answers (2)

sebaferreras
sebaferreras

Reputation: 44669

The thing is that the page is being created only the first time, and then since it already exists, it's not created again. If you need to execute some code every time a tab is selected, use the ionViewDidEnter or the ionViewWillEnter lifecycle hooks:

constructor(...) {
  // Will be executed only once
  // ...
}

ionViewWillEnter() {
  // Will be executed every time the user selects this tab
  // ...
}

// or

ionViewDidEnter() {
  // Will be executed every time the user selects this tab
  // ...
}

Upvotes: 4

Rax Weber
Rax Weber

Reputation: 3780

You can use Lifecycle Hooks in Ionic like so:

ionViewWillEnter {
  // do something when page is about to enter
}

ionViewDidEnter() {
  // do something when page has entered
}

Upvotes: 2

Related Questions