I’m new to ionic/angular and have a seemingly simple question. I want to create a base page, which all authenticated pages inherit from.
I can get this working, but I’m not seeing the ionic lifecycle events called on the base page. I’d rather not call super.ionViewCanEnter();
on every page, for example.
@Component({
selector: 'base-page'
})
export class BasePage {
selector: 'base-page'
constructor(public navCtrl: NavController, public auth: AuthService) {
}
ionViewCanEnter() {
console.log("basepage");
}
}
Are you sure this is possible? Angular introduced component inheritance just a few months ago. Is page inheritance supported?
I’m not sure if it’s possible to trigger ionic lifecycle events on a base page automatically. That’s the root of my question.
It certainly is possible to have a base page, and have inherited pages call super.ionViewCanEnter();
, for example.
Well you got me reading the Angular changelog. Looks as though 2.3 supports inheritance of Angular life cycle hooks. My Ionic 2.00 RC5 wraps Angular 2.2.1. But I haven’t updated in a few weeks. So if you have a version of Ionic that wraps at least Angular 2.3 then you’re getting closer. Whether inheritance supports Ionic life cycle events also, I’m not sure, but if this functionality was added, it must have been added recently.
This looks like the key page: https://github.com/angular/angular/commit/f5c8e09
Edit: Also, if you aren’t using at least Angular 2.3, you’re probably playing with fire if you use page or component inheritance. It looks as though they closed bugs that had previously been open.
Thanks for those links @AaronSterling! I’m not sure exactly what I did wrong, but the Ionic lifecycle hooks in my base page are properly getting triggered when loading pages that extend this object now. Pretty sweet!
Probably you moved, now, all your relevant ionic cycle functions to the super class, and before, you had overwritten those functions without calling them in the super.
Eg (In the page that extends from BasePage ).
ionViewDidLoad() {
super.ionViewDidLoad();
console.log('ionViewDidLoad AdminViewPage');
}
Hi @mflmartin - I haven’t looked too deeply into this, because it’s working the way I want it to already. I’m actually not calling super.ionViewCanEnter()
on the page that extends from the base. That likely would work well if I needed the parent and child to have their own implementation. I actually only need one implementation of ionViewCanEnter
, (in the base page). Having the base page with this method and the child without it seems to work for me - the base page method is always called.
In my case the purpose is to make sure that a user is logged in before loading a page. I only need to do that in one place (base page) and each child doesn’t need a unique implementation too.