Search code examples
angulartypescriptionic-frameworkionic3guard

Ionics 3 Guard issue


I’ve realized that a page gets loaded before ionViewCanEnter decides, I’ve the user is even allowed to view the page.

Therefor, all the components in the template get always constructed.

IMO, this can become really inefficient, especially if the components use http request in their constructor to load data.

Am I getting something wrong or is there a better Guard approach?

Simple Replica

test-page.html

<ion-content>
  <test></test>
</ion-content>

test-page.ts

...
ionViewCanEnter() {
  console.log('ionViewCanEnter?');
  return false;
}
...

test-component.ts

...
constructor() {
  console.log('TestComponent Constructed');
}
...

Console

TestComponent Constructed
ionViewCanEnter?

Solution

  • You're expecting something different which is against the design of the Page/Component in Ionic.

    ionViewCanEnter

    Runs before the view can enter. This can be used as a sort of "guard" in authenticated views where you need to check permissions before the view can enter

    You can see that it says runs before the view can enter.Not before the view has been created.If Page's view has been created means components of that page also being constructed.So that is by design.We cannot do anything for that. But you can change the way where data retrievals of your component. In other words, you need to emit an Event according to the logic of the ionViewCanEnter() and after that, you can subscribe to that event inside your component for data retrievals.After that, you can remove the data retrievals inside the component's constructor. Hope all are working fine after that.